Game of Life
Four rules about neighbours, and gliders start walking across the grid.
Write life(grid, n). grid is an array of rows (y down, x right), each cell 0 for dead or 1 for alive. Run Conway's Game of Life for n generations and return the final grid. Do not change the grid you were given.
In each generation every cell counts its live neighbours among the 8 cells around it. Cells past the edge of the grid count as dead (the world does not wrap). A live cell with 2 or 3 live neighbours stays alive; any other live cell dies. A dead cell with exactly 3 live neighbours comes alive. All cells update at once, from the previous generation.
Call show(grid) with the starting grid and then after every generation, so the stage plays the whole run.
Example: a blinker flips between a row and a column. life([[0, 0, 0], [1, 1, 1], [0, 0, 0]], 1) returns [[0, 1, 0], [0, 1, 0], [0, 1, 0]].
Tests you can see
life([[0,0,0],[1,1,1],[0,0,0]], 1)[[0,1,0],[0,1,0],[0,1,0]]life([[0,0,0,0],[0,1,1,0],[0,1,1,0],[0,0,0,0]], 5)[[0,0,0,0],[0,1,1,0],[0,1,1,0],[0,0,0,0]]life([[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[1,1,1,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]], 4)[[0,0,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],[0,1,1,1,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]]
More tests are hidden. The server runs them all before a time counts.
Call show() while your code works and the run plays back here.
Tab indents · Cmd/Ctrl+Enter runs