Day 6, Year 2015: Probably a Fire Hazard
First read the problem description.
import numpy as np
def new_grid(h, w):
return np.zeros((h, w), dtype=np.int64)
def turn_on(g, f, t, min=0, max=1):
0]:t[0]+1, f[1]:t[1]+1] += 1
g[f[min, max, out=g)
np.clip(g,
def turn_off(g, f, t, min=0, max=1):
0]:t[0]+1, f[1]:t[1]+1] -= 1
g[f[min, max, out=g)
np.clip(g,
def toggle(g, f, t, min=0, max=1):
if min == 0 and max == 1:
0]:t[0]+1, f[1]:t[1]+1] = (g[f[0]:t[0]+1, f[1]:t[1]+1] + 1) % 2
g[f[else:
0]:t[0]+1, f[1]:t[1]+1] += 2
g[f[
min, max, out=g)
np.clip(g,
def action(s):
= None
a if s.startswith('turn on'):
= s[len('turn on '):]
s = 1
a elif s.startswith('turn off'):
= s[len('turn off '):]
s = 2
a elif s.startswith('toggle'):
= s[len('toggle '):]
s = 3
a else:
return None
= s.split(' ')
fields = fields[0].split(',')
f = fields[2].split(',')
t
0] = int(f[0])
f[1] = int(f[1])
f[0] = int(t[0])
t[1] = int(t[1])
t[
return (f, t, a)
def apply_action(g, a, min=0, max=1):
if a[2] == 1:
0], a[1], min, max)
turn_on(g, a[elif a[2] == 2:
0], a[1], min, max)
turn_off(g, a[elif a[2] == 3:
0], a[1], min, max)
toggle(g, a[else:
return
= new_grid(1000, 1000)
g 0,0), (999,999))
turn_on(g, (assert np.sum(g) == 1000*1000
0,0), (999,0))
toggle(g, (assert np.sum(g) == 1000*1000 - 1000
499,499), (500,500))
turn_off(g, (assert np.sum(g) == 1000*1000 - 1000 - 4
import import_ipynb
import helper
= helper.read_file('2015_6.txt') s
= new_grid(1000, 1000)
g for l in s.splitlines():
apply_action(g, action(l))sum(g) np.
569999
= new_grid(1000, 1000)
g for l in s.splitlines():
min=0, max=None)
apply_action(g, action(l), sum(g) np.
17836115
Source code of the solution(s):