Conway's Game of Life
Conways game of life is described here:
You are encouraged to solve this task according to the task description, using any language you may know.
A cell C is represented by a 1 when alive or 0 when dead, in an m-by-m square array of cells. We calculate N - the sum of live cells in C's eight location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (thre adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
Python
<python>import random from collections import defaultdict
printdead, printlive = u'-#' maxgenerations = 3 cellcount = 3,3 celltable = defaultdict(int, {
(1, 2): 1, (1, 3): 1, (0, 3): 1, } )
- Start States
- blinker
u = universe = defaultdict(int) u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1
- toad
- u = universe = defaultdict(int)
- u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
- u[(6,6)], u[(6,7)], u[(6,8)] = 1,1,1
- glider
- u = universe = defaultdict(int)
- maxgenerations = 16
- u[(5,5)], u[(5,6)], u[(5,7)] = 1,1,1
- u[(6,5)] = 1
- u[(7,6)] = 1
- random start
- universe = defaultdict(int,
- # array of random start values
- ( ((row, col), random.choice((0,1)))
- for col in range(cellcount[0])
- for row in range(cellcount[1])
- ) ) # returns 0 for out of bounds
for i in range(maxgenerations):
print "\nGeneration %3i:" % ( i, ) for row in range(cellcount[1]): print " ", .join(str(universe[(row,col)]) for col in range(cellcount[0])).replace( '0', printdead).replace('1', printlive) nextgeneration = defaultdict(int) for row in range(cellcount[1]): for col in range(cellcount[0]): nextgeneration[(row,col)] = celltable[ ( universe[(row,col)], -universe[(row,col)] + sum(universe[(r,c)] for r in range(row-1,row+2) for c in range(col-1, col+2) ) ) ] universe = nextgeneration</python>
Sample output:
Generation 0: --- ### --- Generation 1: -#- -#- -#- Generation 2: --- ### ---