2015-12-18 = Like a GIF For Your Yard
(original .ipynb)
Puzzle input is a grid of lights, composed of '#' (meaning "on") and '.' (meaning "off"). Part one involves applying a set of Game Of life type instructions and counting how many lights are "on" after 100 time steps. Part two involves doing the same but forcing the corner lights to always be on.
from advent import neighbours8 puzzle_input_str = open("./puzzle_input/day18.txt").read() test_input_str = """.#.#.# ...##. #....# ..#... #.#..# ####..""" def next_state(grid, r, c): light = grid[r][c] on_neighbours = len([grid[nr][nc] for nr,nc in neighbours8(grid, r, c) if grid[nr][nc]]) if light and (on_neighbours == 2 or on_neighbours == 3): return True elif (not light) and on_neighbours == 3: return True return False def step_grid(grid): next_grid = [] for r, row in enumerate(grid): next_row = [] for c, col in enumerate(row): next_row.append(next_state(grid, r, c)) next_grid.append(next_row) return next_grid def nop(grid): pass def part_one(input_str, steps=100, postprocess=nop): grid = [ [True if c == "#" else False for c in line] for line in input_str.split("\n") ] postprocess(grid) for _ in range(steps): grid = step_grid(grid) postprocess(grid) return sum( sum(1 for col in row if col) for row in grid ) assert 4 == part_one(test_input_str, 4) print("part one:", part_one(puzzle_input_str))
part one: 768
def turn_corners_on(grid): last_row = len(grid) - 1 last_col = len(grid[0]) - 1 grid[0][0] = True grid[0][last_col] = True grid[last_row][0] = True grid[last_row][last_col] = True def part_two(input_str, steps=100): return part_one(input_str, steps, turn_corners_on) assert 17 == part_two(test_input_str, 5) print("part two:", part_two(puzzle_input_str))
part two: 781