Skip to content

Instantly share code, notes, and snippets.

@rolisz
Created December 8, 2012 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolisz/4242046 to your computer and use it in GitHub Desktop.
Save rolisz/4242046 to your computer and use it in GitHub Desktop.
Functional Conway's Game of Life
import copy
def next_state(current_state, nr_neighbors):
if (current_state and (nr_neighbors < 2 or nr_neighbors > 3)) or\
(not current_state and nr_neighbors == 3):
return not current_state
return current_state
def are_neighbors(cell1,cell2):
return abs(cell1[0] - cell2[0]) <= 1 and abs(cell1[1] - cell2[1]) <= 1 \
and cell1 != cell2
def nr_alive_neighbors(alive_cells,cell):
if not alive_cells:
return 0
return are_neighbors(cell,alive_cells[0]) + nr_alive_neighbors(alive_cells[1:],cell)
def dead_neighbors(alive_cells,cell):
return {(i,j) for i in range(cell[0]-1,cell[0]+2) for j in range(cell[1]-1,cell[1]+2)
if are_neighbors(cell,(i,j)) and (i,j) not in alive_cells}
def tick(cells):
deadNeighbors = set()
cellCopy = [cell for cell in cells if next_state(True,nr_alive_neighbors(cells,cell))]
deadNeighbors = {dead_cell for cell in cells for dead_cell in dead_neighbors(cells,cell)}
cellCopy.extend(cell for cell in deadNeighbors if next_state(False,nr_alive_neighbors(cells,cell)))
return cellCopy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment