about summary refs log blame commit diff stats
path: root/swift/life/Sources/main.swift
blob: 4b3e7a6c4dba485d55d15e41649dae181a07b498 (plain) (tree)




















































                                                                                           
import Foundation

let rows = 10
let cols = 10
var board = Array(repeating: Array(repeating: 0, count: cols), count: rows)

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
        }
    }
}

board[1][2] = 1
board[2][3] = 1
board[3][1] = 1
board[3][2] = 1
board[3][3] = 1

for _ in 0..<10 {
    printBoard(board)
    board = nextGeneration(board)
    sleep(1) // FIXME: figure out how to sleep for periods shorter than a full second
}