Skip to content
advent of code 2015

day 18

like a gif for your yard

approach

lights are stored as 1 (on) or -1 (off). a step is done in place in two passes: the first adds the number of lit neighbours to lit cells and subtracts it from dark ones, and since the sign still tells the old state, the second pass can decode each cell back to 1 or -1 by its value.

part 1 runs 100 steps and counts the lights. part 2 passes the four corners as an extra list that is forced on before the first step and after every step.

the trick

encode the neighbour count into the cell while keeping its sign, so the grid updates in place without a copy.

python
def step(grid):
    for r, c in product(range(len(grid)), range(len(grid[0]))):
        onn = sum(1 for nr, nc in neighbors(grid, r, c) if grid[nr][nc]>0)
        if grid[r][c] == 1:
            grid[r][c] += onn
        else:
            grid[r][c] -= onn
    for r, c in product(range(len(grid)), range(len(grid[0]))):
        if grid[r][c] > 0: # it is on
            grid[r][c] = 1 if grid[r][c] == 3 or grid[r][c] == 4 else -1
        else:
            grid[r][c] = 1 if grid[r][c] == -4 else -1