diff options
author | elioat <elioat@tilde.institute> | 2024-06-20 18:32:33 -0400 |
---|---|---|
committer | elioat <elioat@tilde.institute> | 2024-06-20 18:32:33 -0400 |
commit | 05a1adcbedb43920074c1854338d6ffc635093f8 (patch) | |
tree | 78a731b7a6df0efe5844e520e2372a18a720fcb8 /swift/life | |
parent | f59bcfbea9ae93d945c0ef3dcbf2bb5b184fc0a3 (diff) | |
download | tour-05a1adcbedb43920074c1854338d6ffc635093f8.tar.gz |
*
Diffstat (limited to 'swift/life')
-rw-r--r-- | swift/life/Sources/main.swift | 20 |
1 files changed, 19 insertions, 1 deletions
diff --git a/swift/life/Sources/main.swift b/swift/life/Sources/main.swift index b27bcba..3b9f74a 100644 --- a/swift/life/Sources/main.swift +++ b/swift/life/Sources/main.swift @@ -13,27 +13,45 @@ func printBoard(_ board: [[Int]]) { print("\n") } +// are these comments enough for a blog post? func countLiveNeighbors(_ board: [[Int]], x: Int, y: Int) -> Int { + // All of the possible directions to check for live neighbors let directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] + + // Iterate over the directions and count live neighbors return directions.reduce(0) { count, dir in + // Calculate the coordinates of the neighbor cell let newX = x + dir.0 let newY = y + dir.1 + + // Check if the neighbor cell is within the bounds of the board if newX >= 0 && newX < rows && newY >= 0 && newY < cols { + // If the neighbor cell is within bounds, add its value to the count return count + board[newX][newY] } + + // If the neighbor cell is out of bounds, ignore it and continue with the next direction return count } } func nextGeneration(_ currentBoard: [[Int]]) -> [[Int]] { + // Iterate over each cell in the current board return currentBoard.enumerated().map { (x, row) in return row.enumerated().map { (y, cell) in + // Count the number of live neighbors for the current cell let liveNeighbors = countLiveNeighbors(currentBoard, x: x, y: y) + + // Determine the next state of the cell if cell == 1 && (liveNeighbors < 2 || liveNeighbors > 3) { + // Determine death return 0 } else if cell == 0 && liveNeighbors == 3 { + // Determine life return 1 } + + // Do nothing return cell } } @@ -86,4 +104,4 @@ rpentomino[3][5] = 1 rpentomino[4][3] = 1 rpentomino[4][4] = 1 rpentomino[5][4] = 1 -simulate(board: rpentomino, generations: 100) \ No newline at end of file +simulate(board: rpentomino, generations: 22) \ No newline at end of file |