Skip to content

Instantly share code, notes, and snippets.

@ewindisch
Created March 22, 2013 11:21
Show Gist options
  • Save ewindisch/5220575 to your computer and use it in GitHub Desktop.
Save ewindisch/5220575 to your computer and use it in GitHub Desktop.
Hashed Game of life in Python
#!/usr/bin/env python2.7
def mkboard(seed):
columns = {}
# Need not be efficient while seed is small.
for i in seed:
column = set()
while seed[i].count(1) > 0:
e = seed[i].index(1)
# Thank laziness for mutability.
seed[i][e] = 0
column.add(e)
columns[i] = column
return columns
def gol(columns):
delta = {}
collect = set()
while True:
for coln in columns:
column = columns[coln]
# empty column
if len(column) == 0:
collect.add(coln)
continue
delta[coln] = set()
for lifeform in column:
# neighbors
# TODO - make terser
nei = (lifeform + 1 in column) + \
(lifeform - 1 in column)
if (coln - 1) in columns:
nei += (lifeform in columns[coln - 1]) + \
(lifeform - 1 in columns[coln - 1]) + \
(lifeform + 1 in columns[coln - 1])
if (coln + 1) in columns:
nei += (lifeform in columns[coln + 1]) + \
(lifeform - 1 in columns[coln + 1]) + \
(lifeform + 1 in columns[coln + 1])
# If we have exactly 2 neighbors, then
# we probably have an adjacent empty cell,
# it subsequently will have 3 neighbors,
# that cell must become 'live'.
# TODO - make terser
if nei == 2:
for i in (lifeform + 1, lifeform - 1):
if i not in column:
delta[coln].add(lifeform)
for i in (coln - 1, coln +1):
for l in (lifeform, lifeform + 1, lifeform - 1):
if l not in columns.get(i, set()):
if i not in delta:
delta[i] = set()
delta[i].add(l)
if nei < 2 or nei > 3:
# Discard lifeform
delta[coln].add(lifeform)
# implicitly, all other cases are nei == 2 | 3
# flip based on the delta.
# i.e. apply this generation before starting next.
for coln in delta:
if not coln in columns:
columns[coln] = set()
columns[coln] ^= delta[coln]
# Garbage collect
for garbage in collect:
del columns[garbage]
if garbage in delta:
del delta[garbage]
collect.clear()
# Print the board on each turn.
print columns
if __name__ == "__main__":
seed = {}
seed[0] = [1, 1, 1]
#seed[1] = [1, 1, 0]
#seed[2] = [0, 0, 1]
columns = mkboard(seed)
gol(columns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment