import Foundation let rows = 10 let cols = 10 func printBoard(_ board: [[Int]]) { board.forEach { row in row.forEach { cell in print(cell == 1 ? "@" : ".", terminator: "") } print() } print("\n") } func countLiveNeighbors(_ board: [[Int]], x: Int, y: Int) -> Int { let directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] return directions.reduce(0) { count, dir in let newX = x + dir.0 let newY = y + dir.1 if newX >= 0 && newX < rows && newY >= 0 && newY < cols { return count + board[newX][newY] } return count } } func nextGeneration(_ currentBoard: [[Int]]) -> [[Int]] { return currentBoard.enumerated().map { (x, row) in return row.enumerated().map { (y, cell) in let liveNeighbors = countLiveNeighbors(currentBoard, x: x, y: y) if cell == 1 && (liveNeighbors < 2 || liveNeighbors > 3) { return 0 } else if cell == 0 && liveNeighbors == 3 { return 1 } return cell } } } func simulate(board: [[Int]], generations: Int) { var currentBoard = board for _ in 0..