Advent of Code 2015 Day 6

Author

Nathan Moore

— Day 6: Probably a Fire Hazard —

Santa has given you some instructions for how to turn on and turn off a grid of lights.

After following the instructions, how many lights are lit?

import re
import numpy as np

with open('data-2015-06.txt', 'r') as f:
    instructions = f.read().splitlines()

Prepare the instructions

ins = [[0] * 5 for _ in range(len(instructions))]
reg1 = r'^(.+?)\d'
reg2 = r' (\d.*?),'
reg3 = r',(\d{1,3})'

for i in range(len(instructions)):
    ins[i][0] = re.findall(reg1, instructions[i])[0].strip() # instruction
    ins[i][1] = int(re.findall(reg2, instructions[i])[0].strip()) # x1
    ins[i][2] = int(re.findall(reg3, instructions[i])[0].strip()) # y1
    ins[i][3] = int(re.findall(reg2, instructions[i])[1].strip()) # x2
    ins[i][4] = int(re.findall(reg3, instructions[i])[1].strip()) # y2

Create the grid of lights

lights = np.full((1000, 1000), False)

Apply the instructions

for i in ins:
    if i[0] == 'turn on':
        lights[i[1]:i[3]+1, i[2]:i[4]+1] = True
    elif i[0] == 'turn off':
        lights[i[1]:i[3]+1, i[2]:i[4]+1] = False
    else:       # toggle
        for x in range(i[1], i[3] + 1):
            for y in range(i[2], i[4] + 1):
                lights[x, y] = not lights[x, y]

How many lights are on?

lights.sum()

# 377891
np.int64(377891)

— Part Two —

The instructions are more complicated, increasing and decreasing brightness.

What is the total brightness of all lights combined after following Santa’s instructions?

# This time we are tracking brightness so start with zeros
lights = np.full((1000, 1000), 0)

Modify our instructions

for i in ins:
    if i[0] == 'turn on':
        lights[i[1]:i[3]+1, i[2]:i[4]+1] = lights[i[1]:i[3]+1, i[2]:i[4]+1] + 1
    elif i[0] == 'turn off':
        lights[i[1]:i[3]+1, i[2]:i[4]+1] = lights[i[1]:i[3]+1, i[2]:i[4]+1] - 1
        np.place(lights, lights<0, 0)
    else:       # toggle
        lights[i[1]:i[3]+1, i[2]:i[4]+1] = lights[i[1]:i[3]+1, i[2]:i[4]+1] + 2

Sum of the brightness

lights.sum()

# 14110788
np.int64(14110788)