Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Life Counter by tom-tom
from collections import Counter
def life_counter(state, tick_n):
live_cells = {(i, j) for j, row in enumerate(state)
for i, cell in enumerate(row) if cell}
neighbours = Counter()
for _ in range(tick_n):
neighbours.clear()
for i, j in live_cells:
for x in i - 1, i, i + 1:
for y in j - 1, j, j + 1:
neighbours[(x, y)] += 1
live_cells = {cell for cell, count in neighbours.items()
if count == 3 or count == 4 and cell in live_cells} #live +1 for itself
return len(live_cells)
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) == 16, "Stones"
Aug. 7, 2017