Skip to content
advent of code 2015

day 06

probably a fire hazard

approach

a regex pulls the operation and the two corners out of each line. the grid is a plain 1000×1000 list of lists and every instruction loops over its rectangle.

part 1 toggles with 1 - x or sets cells to 0 or 1, then sums the grid. part 2 reuses the same loop with a delta (+1, -1, +2) clamped at zero. the file also starts a fenwick tree (add and query) that ends up unused; the brute-force rectangles are what runs.

the trick

one clamped add over a rectangle covers all three operations of part 2.

python
def add(grid, r1, c1, r2, c2, delta):
    for r in range(r1, r2 + 1):
        for c in range(c1, c2 + 1):
            grid[r][c] = max(0, grid[r][c] + delta)