Advertisement
usesbiggerwords

AoC 2021 Day 11

Dec 12th, 2021
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import numpy as np
  2. import os
  3.  
  4.  
  5. ALL_FLASHING = np.zeros((10, 10), dtype=np.int32)
  6.  
  7.  
  8. def read_and_init(fn):
  9.     with open(fn, 'r') as f:
  10.         lines = f.read().splitlines()
  11.     grid = [[int(x) for x in line] for line in lines]
  12.     oktapodi = np.array(grid, dtype=np.int32)
  13.     return oktapodi
  14.  
  15.  
  16. def run(octopi: np.ndarray, part: int):
  17.     flashes = 0
  18.     i = 0
  19.     while True:
  20.         octopi += 1
  21.         flashed = set()
  22.         f = np.where(octopi == 10)
  23.         flashing = [(f[0][i], f[1][i]) for i in range(len(f[0]))]
  24.         while flashing:
  25.             r, c = flashing.pop(0)
  26.             flashed.add((r, c))
  27.             r0, r1 = max(r-1, 0), max(r+2, 0)
  28.             c0, c1 = max(c-1, 0), max(c+2, 0)
  29.             neighbors = octopi[r0:r1, c0:c1]
  30.             neighbors += 1
  31.             f = np.where(neighbors == 10)
  32.             flashing_neighbors = [(f[0][i] + r0, f[1][i] + c0) for i in range(len(f[0]))]
  33.             flashing += flashing_neighbors
  34.         for r, c in flashed:
  35.             octopi[r, c] = 0
  36.         flashes += octopi.size - np.count_nonzero(octopi)
  37.         i += 1
  38.         if part == 1 and i == 100:
  39.             print('Part 1:', flashes)
  40.             break
  41.         if part == 2:
  42.             export_image(octopi, i)
  43.             if np.all(octopi == ALL_FLASHING):
  44.                 print('Part 2: ', i)
  45.         if i == 500:
  46.             break
  47.  
  48.  
  49. oktos = read_and_init(os.path.dirname(__file__) + '\\in.txt')
  50. run(oktos, 1)
  51. oktos = read_and_init(os.path.dirname(__file__) + '\\in.txt')
  52. run(oktos, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement