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..<generations {
printBoard(currentBoard)
currentBoard = nextGeneration(currentBoard)
sleep(1) // FIXME: figure out how to sleep for periods shorter than a full second
}
}
var glider = Array(repeating: Array(repeating: 0, count: cols), count: rows)
glider[1][2] = 1
glider[2][3] = 1
glider[3][1] = 1
glider[3][2] = 1
glider[3][3] = 1
simulate(board: glider, generations: 10)
var flasher = Array(repeating: Array(repeating: 0, count: cols), count: rows)
flasher[4][5] = 1
flasher[5][5] = 1
flasher[6][5] = 1
simulate(board: flasher, generations: 4)
var beacon = Array(repeating: Array(repeating: 0, count: cols), count: rows)
beacon[2][2] = 1
beacon[2][3] = 1
beacon[3][2] = 1
beacon[4][5] = 1
beacon[5][4] = 1
beacon[5][5] = 1
simulate(board: beacon, generations: 4)
var toad = Array(repeating: Array(repeating: 0, count: cols), count: rows)
toad[3][4] = 1
toad[3][5] = 1
toad[3][6] = 1
toad[4][3] = 1
toad[4][4] = 1
toad[4][5] = 1
simulate(board: toad, generations: 5)
var rpentomino = Array(repeating: Array(repeating: 0, count: cols), count: rows)
rpentomino[3][4] = 1
rpentomino[3][5] = 1
rpentomino[4][3] = 1
rpentomino[4][4] = 1
rpentomino[5][4] = 1
simulate(board: rpentomino, generations: 100)