Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Life Counter by Tinus_Trotyl
def life_counter(state, tick_n):
state = [list(row) for row in state]
roundabout = ((-1,-1), ( 0,-1), ( 1,-1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1))
def count(x0, y0, state):
### count surrounding life cells ###
counter = 0
mx, my = len(state[0]), len(state)
for dx, dy in roundabout:
x, y = x0 + dx, y0 + dy
if 0 <= x < mx and 0 <= y < my: counter += state[y][x]
return counter
for n in range(tick_n):
### expand state if needed ###
if 1 in [row[-1] for row in state]: state = [row + [0] for row in state]
if 1 in state[0]: state = [[0 for c in state[0]]] + state
if 1 in [row[0] for row in state]: state = [[0] + row for row in state]
if 1 in state[-1]: state = state + [[0 for c in state[0]]]
### update state one life step to newstate ###
mx, my = len(state[0]), len(state)
newstate = [[0 for x in range(mx)] for y in range(my)]
for y in range(my):
for x in range(mx):
neighbors = count(x, y, state)
if neighbors == 3: newstate[y][x] = 1
if state[y][x] and neighbors == 2: newstate[y][x] = 1
### undo newstate from unneeded edge rows and -collumns ###
if not 1 in [c for row in newstate for c in row[-2:]]: newstate = [row[:-1] for row in newstate]
if not 1 in (newstate[0] + newstate[1]): newstate = newstate[1:]
if not 1 in [c for row in newstate for c in row[:2]]: newstate = [row[1:] for row in newstate]
if not 1 in (newstate[-2] + newstate[-1]): newstate = newstate[:-1]
### update state (return from newstate) ###
state = [[c for c in row] for row in newstate]
return sum(sum(row) for row in state)
April 12, 2019
Comments: