Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2015-12-06 - Probably a Fire Hazard

(original .ipynb)

Puzzle input is a sequence of instructions which control sections of a grid of light. In part one we interpret the instructions as simply switching the lights between on or off states, and finding how many are still on after all the instructions are applied. In part two we interpret them as controlling brightness levels of individual lights, and finding the sum of each light's brightness levels.

puzzle_input_str = open("./puzzle_input/day6.txt").read()

toggle   = lambda state: not state
turn_on  = lambda state: True
turn_off = lambda state: False


def parse_range(tokens):
    start_x_str, start_y_str = tokens[0].split(",")
    end_x_str, end_y_str = tokens[2].split(",")
    return (int(start_x_str), int(start_y_str), int(end_x_str), int(end_y_str))


def parse_instructions(tokens):
    if tokens[1] == "on":
        return turn_on, parse_range(tokens[2:])
    
    if tokens[1] == "off":
        return turn_off, parse_range(tokens[2:])
    
    return toggle, parse_range(tokens[1:])


def apply_instruction(grid, instruction):
    action, ranges = instruction
    start_x, start_y, end_x, end_y = ranges
    x = start_x
    while x <= end_x:
        y = start_y
        while y <= end_y:
            grid[x][y] = action(grid[x][y])
            y += 1
        x += 1


def init_grid():
    for _ in range(1000):
        yield [False] * 1000


def part_one(input_str):
    grid = list(init_grid())
    instructions = [parse_instructions(line.split(" ")) for line in input_str.split("\n")]    
    
    for instruction in instructions:
        apply_instruction(grid, instruction)
    
    count = 0
    for row in grid:
        count += sum(int(c) for c in row)
    
    return count


print("part one:", part_one(puzzle_input_str))
part one: 569999
toggle   = lambda brightness: brightness + 2
turn_on  = lambda brightness: brightness + 1
turn_off = lambda brightness: brightness - 1 if brightness > 0 else 0


def init_grid():
    for _ in range(1000):
        yield [0] * 1000

        
def part_two(input_str):
    grid = list(init_grid())
    instructions = [parse_instructions(line.split(" ")) for line in input_str.split("\n")]    
    
    for instruction in instructions:
        apply_instruction(grid, instruction)
    
    count = 0
    for row in grid:
        count += sum(int(c) for c in row)
    
    return count


print("part two:", part_two(puzzle_input_str))
part two: 17836115