Advertisement
hhoppe

Advent of code 2024 day 14

Dec 14th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. import hhoppe_tools as hh
  2. import mediapy as media
  3.  
  4. def day14(s, *, part2=False, shape=(103, 101), steps=100, visualize=False, rep=2, fps=50):
  5.   values = np.array([re.findall(r'[-\d]+', line) for line in s.splitlines()], int)
  6.   yxs0, dyxs = values[:, 1::-1], values[:, 3:1:-1]
  7.  
  8.   if not part2:
  9.     yxs = (yxs0 + steps * dyxs) % shape
  10.     count = np.zeros(shape, int)
  11.     for yx in yxs:
  12.       count[tuple(yx)] += 1
  13.     ym, xm = shape[0] // 2, shape[1] // 2
  14.     quadrants = [[g[:, :xm], g[:, xm + 1 :]] for g in [count[:ym], count[ym + 1 :]]]
  15.     return math.prod(q.sum() for row in quadrants for q in row)
  16.  
  17.   def variance(t: int, axis: int) -> float:
  18.     return np.var((yxs0[:, axis] + t * dyxs[:, axis]) % shape[axis])
  19.  
  20.   # We expect the pixel positions in the "tree" image to have lowest variance in both Y and X.
  21.   moduli = shape
  22.   remainders = [min(range(moduli[axis]), key=lambda t: variance(t, axis)) for axis in range(2)]
  23.   t = hh.solve_modulo_congruences(remainders, moduli)
  24.  
  25.   if visualize:
  26.     images = []
  27.     for step in range(t + 1):
  28.       if step > 100 and step % moduli[0] != remainders[0] and step % moduli[1] != remainders[1]:
  29.         continue
  30.       yxs = (yxs0 + step * dyxs) % shape
  31.       mask = np.full(shape, False)
  32.       mask[tuple(yxs.T)] = True
  33.       image = hh.to_image(mask, 250, 0).repeat(rep, 0).repeat(rep, 1)
  34.       text = f'Step{step:5}'
  35.       hh.overlay_text(image, (10, 120), text, fontsize=14, background=250, align='tl', margin=3)
  36.       images.append(image)
  37.     images = [images[0]] * int(fps * 1.5) + images + [images[-1]] * int(fps * 3)
  38.     media.show_video(images, codec='gif', fps=fps, title='day14')
  39.  
  40.   return t
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement