def step(grid: Grid): for y in range(grid.height): for x in range(grid.width): p = Position(x, y) grid.set(p, grid.get(p) + 1) flashed = set() while True: c = len(flashed) for y in range(grid.height): for x in range(grid.width): p = Position(x, y) if grid.get(p) > 9: if p not in flashed: flash(grid, p, flashed) if len(flashed) == c: break for p in flashed: grid.set(p, 0) return len(flashed)
def main(): instructions = [Instruction.from_string(line.strip()) for line in open("day06.input").readlines()] # Part 1 grid = Grid(1000, 1000, False) for i in instructions: for y in range(i.fr.y, i.to.y+1): for x in range(i.fr.x, i.to.x+1): match i.op: case "toggle": grid.set(Position(x, y), not grid.get(Position(x, y))) case "on": grid.set(Position(x, y), True) case "off": grid.set(Position(x, y), False) print("Part one:", grid.count(True)) # Part 2 grid = Grid(1000, 1000, 0) for i in instructions: for y in range(i.fr.y, i.to.y+1): for x in range(i.fr.x, i.to.x+1): match i.op: case "toggle": grid.set(Position(x, y), grid.get(Position(x, y)) + 2) case "on": grid.set(Position(x, y), grid.get(Position(x, y)) + 1) case "off": grid.set(Position(x, y), max(0, grid.get(Position(x, y)) - 1)) print("Part two:", sum(node for node in grid.nodes))
def test_get(): gr = Grid(TEST_GRID_IRREG, rectangular=False) assert (gr.get(0, 0) == ' ') assert (gr.get(2, 1) == '#') assert (gr.get(1, 3) == '.')
def flash(grid: Grid, p: Position, flashed): flashed.add(p) for n in grid.neighbours(p, diagonal=True): grid.set(n, grid.get(n) + 1)