2021-12-10 21:44:57 -08:00

#### 79 lines 1.5 KiB Python Raw Permalink Blame History

 ```class Boi(object): ``` ``` def __init__(self, num): ``` ``` self.num = num ``` ``` self.flashed = False ``` ``` ``` ``` def __repr__(self): ``` ``` return str(self.num) ``` ``` ``` ``` ``` ```bois = {} ``` ``` ``` ```with open("input.txt") as f: ``` ``` y = 0 ``` ``` for line in f.readlines(): ``` ``` x = 0 ``` ``` for c in line.strip(): ``` ``` bois[(x, y, )] = Boi(int(c)) ``` ``` x += 1 ``` ``` y += 1 ``` ``` ``` ``` ``` ```def neighbors(point): ``` ``` l = [] ``` ``` for dx in range(-1, 2): ``` ``` for dy in range(-1, 2): ``` ``` p = (point[0] + dx, point[1] + dy, ) ``` ``` if p == point: ``` ``` continue ``` ``` try: ``` ``` l.append(bois[p]) ``` ``` except KeyError: ``` ``` pass ``` ``` return l ``` ``` ``` ``` ``` ```def simulate(): ``` ``` flashes = 0 ``` ``` # import pdb ``` ``` # pdb.set_trace() ``` ``` # perform 1 step of simulation ``` ``` ``` ``` # incr all bois by 1 ``` ``` for boi in bois.values(): ``` ``` boi.num += 1 ``` ``` ``` ``` while True: ``` ``` hit = [] ``` ``` # flash all bois > 9 ``` ``` for point, boi in bois.items(): ``` ``` if boi.num > 9 and not boi.flashed: ``` ``` flashes += 1 ``` ``` boi.num = 0 ``` ``` boi.flashed = True ``` ``` hit.extend(neighbors(point)) ``` ``` ``` ``` # increment all bois that are hit by the flash ``` ``` for neighbor in hit: ``` ``` neighbor.num += 1 ``` ``` ``` ``` if not hit: ``` ``` break ``` ``` ``` ``` # reset flashes ``` ``` for boi in bois.values(): ``` ``` if boi.flashed: ``` ``` boi.num = 0 ``` ``` boi.flashed = False ``` ``` ``` ``` return flashes ``` ``` ``` ``` ``` ```s = 0 ``` ```for wave in range(0, 100): ``` ``` f = simulate() ``` ``` print("wave", wave, "flashes", f) ``` ``` s += f ``` ``` ``` ```print(s) ```