Skip to content

Instantly share code, notes, and snippets.

@mdiazv
Last active May 13, 2017 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdiazv/e478648a9eb382b8d16c to your computer and use it in GitHub Desktop.
Save mdiazv/e478648a9eb382b8d16c to your computer and use it in GitHub Desktop.
Functional Conway's Game of Life (python 2.7)
from __future__ import print_function
M = 5
N = 10
w = [
[0,1,0,1,1,0,0,1,0,1],
[0,1,0,1,1,0,0,1,0,1],
[0,1,0,1,1,0,0,1,0,1],
[0,1,0,1,1,0,0,1,0,1],
[0,1,0,1,1,0,0,1,0,1],
]
def get(w, i, j):
return 0 if i < 0 or j < 0 or i >= M or j >= N else w[i][j]
def neighbors(w, i, j):
return sum(get(w, ii, jj) for ii in xrange(i-1, i+2) for jj in xrange(j-1, j+2) if ii != i or jj != j)
def cell_nextgen(w, i, j):
n = neighbors(w, i, j)
return 1 if n == 3 else get(w, i, j) if n == 2 else 0
def nextgen(w):
return [[cell_nextgen(w, i, j) for j in xrange(N)] for i in xrange(M)]
def pprint(w):
map(print, w)
def conway(w, g):
print(' --- {} --- '.format(g))
pprint(w)
n = nextgen(w)
return g if n == w else conway(n, g+1)
conway(w, 0)
@mdiazv
Copy link
Author

mdiazv commented Nov 15, 2015

This is a followup after the Global Day of Code Retreat 2015.
Time: 45 minutes
Ruleset: Functional style

  • No loops
  • No mutation
  • Only declarations and return statements
  • No side effects (other than I/O)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment