Last active
May 13, 2017 07:55
-
-
Save mdiazv/e478648a9eb382b8d16c to your computer and use it in GitHub Desktop.
Functional Conway's Game of Life (python 2.7)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a followup after the Global Day of Code Retreat 2015.
Time: 45 minutes
Ruleset: Functional style