Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Life Counter by Sim0000
def life_counter(state, tick_n):
live = {(x,y) for y in range(len(state)) for x in range(len(state[0])) if state[y][x]}
for _ in range(tick_n):
next_live = set()
born_candidate = set()
# Any live cell with two or three live neighbours lives on to the next generation.
for x, y in live:
neighbor = {(x+i, y+j) for i in (-1,0,1) for j in (-1,0,1) if not i==j==0}
if len(neighbor & live) in (2, 3): next_live |= {(x, y)}
born_candidate |= neighbor - live
# Any dead cell with exactly three live neighbours becomes a live cell.
for x, y in born_candidate:
neighbor = {(x+i, y+j) for i in (-1,0,1) for j in (-1,0,1) if not i==j==0}
if len(neighbor & live) == 3: next_live |= {(x, y)}
live = next_live
return len(live)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert life_counter(((0, 1, 0, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 1, 1),
(0, 0, 0, 0, 0, 1, 1),
(0, 0, 0, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0)), 4) == 15, "Example"
assert life_counter(((0, 1, 0, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 1, 1),
(0, 0, 0, 0, 0, 1, 1),
(0, 0, 0, 0, 0, 0, 0),
(1, 1, 1, 0, 0, 0, 0)), 15) == 14, "Little later"
assert life_counter(((0, 1, 0),
(0, 0, 1),
(1, 1, 1)), 50) == 5, "Glider"
assert life_counter(((1, 1, 0, 1, 1),
(1, 1, 0, 1, 1),
(0, 0, 0, 0, 0),
(1, 1, 0, 1, 1),
(1, 1, 0, 1, 1)), 100), "Stones"
Sept. 30, 2014