From 05a1adcbedb43920074c1854338d6ffc635093f8 Mon Sep 17 00:00:00 2001 From: elioat Date: Thu, 20 Jun 2024 18:32:33 -0400 Subject: * --- swift/life/Sources/main.swift | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'swift/life') 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 -- cgit 1.4.1-2-gfad0 ac0e9b00e40d5cd49cc'>plain) (tree)