Part 1
For this puzzle, we need to simulate a simplified version of Conway's Game of Life. Each cell individually either turns on or off based on the number of turned-on neighbors. In contrast to a normal game of life, there is a fixed grid size of 100x100. We are asked to find the number of on cells after 100 time steps.
To implement this, we start with an numpy grid of size 102x102. This includes the edges around the grid we are interested in and simplifies handling later on. In each step, we iterate over each cell and count the number of neighboring cells in the on state. Based on that, we set the state for each cell in the next time step.
def part_1(field):
for stepno in range(100):
new_field = np.zeros((FIELD_SIZE + 2, FIELD_SIZE + 2), dtype=np.int8)
for x in range(1, FIELD_SIZE + 1):
for y in range(1, FIELD_SIZE + 1):
current = field[x,y]
numneighbors = field[x-1:x+2,y-1:y+2].sum() - current
if current == 1:
if numneighbors in [2,3]:
new_field[x, y] = 1
else:
new_field[x, y] = 0
if current == 0:
if numneighbors == 3:
new_field[x, y] = 1
else:
new_field[x, y] = 0
field = new_field
return field.sum()
Running the code took a few seconds, but yielded the correct solution.
Part 2
In part 2, we add the rule that each corner is always turned on. This is done in two steps: During the initialization we explicitly set the corners to on. Secondly during the time step we handle the corners seperately and just set them to on instead of counting the neighbors.
...
if (x == 1 and y == 1) \
or (x == 1 and y == FIELD_SIZE) \
or (x == FIELD_SIZE and y == 1) \
or (x == FIELD_SIZE and y == FIELD_SIZE):
new_field[x,y] = 1
continue
...
Running it took a few seconds again.
No comments:
Post a Comment