advent2021/eleven.py

51 lines
1.1 KiB
Python
Executable File

#!/usr/bin/env python3
from useful import *
flashes = 0
def parseline(s):
return [int(c) for c in s]
def convolve(a):
w, h = a.shape
b = np.pad(a, (1, 1))
return sum(b[x+1:x+1+w,y+1:y+1+h] for x in range(-1, 2) for y in range(-1, 2))
def spill(a, burnt=None):
global flashes
blaze = (a > 9).astype('int')
if not blaze.any():
return a
flashes += np.sum(blaze)
now_burnt = np.logical_or(burnt, blaze)
return spill((a + convolve(blaze)) * np.logical_not(now_burnt), now_burnt)
def step(a):
retval = spill(a+1)
try:
if sys.argv[1] == '-v':
cv.imshow('eleven', retval.astype('uint8') * (255//9))
cv.waitKey(40)
except IndexError:
pass
return retval
with open(0) as f:
grid = np.asarray([parseline(l) for l in lines(f)])
# part 1
for i in range(100):
grid = step(grid)
print(flashes)
i += 1 # python's for loop indices are not like c's
# part 2 (only works if the answer is above 100)
while True:
grid = step(grid)
if(np.sum(grid) == 0):
print(i + 1)
break
i += 1