Advertisement
hhoppe

Advent of code 2022 day 20

Dec 21st, 2022
964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. # Using numba with doubly-linked list approach adapted from
  2. # https://github.com/shaeberling/euler/blob/master/kotlin/src/com/s13g/aoc/aoc2022/Day20.kt
  3.  
  4. @numba.njit
  5. def day20_mix(a):
  6.   for i in range(len(a)):  # pylint: disable=consider-using-enumerate
  7.     value, prev_, next_ = a[i]
  8.     offset = value % (len(a) - 1)
  9.     if offset != 0:
  10.       a[next_, 1], a[prev_, 2] = prev_, next_  # Disconnect node i.
  11.       prev_ = i
  12.       if offset < len(a) // 2:
  13.         for _ in range(offset):
  14.           prev_ = a[prev_, 2]
  15.       else:
  16.         for _ in range(len(a) - offset):
  17.           prev_ = a[prev_, 1]
  18.       next_ = a[prev_, 2]
  19.       a[i, 1], a[i, 2], a[prev_, 2], a[next_, 1] = prev_, next_, i, i  # Reconnect node i.
  20.  
  21.  
  22. def day20(s, *, part2=False):
  23.   a = np.array(list(map(int, s.splitlines())))
  24.   a *= 811_589_153 if part2 else 1
  25.   a = np.array([[value, (i - 1) % len(a), (i + 1) % len(a)] for i, value in enumerate(a)])
  26.   for _ in range(10 if part2 else 1):
  27.     day20_mix(a)
  28.  
  29.   (i,), = np.nonzero(a[:, 0] == 0)
  30.   values = []
  31.   for _ in range(len(a)):
  32.     values.append(a[i, 0])
  33.     i = a[i, 2]
  34.   return sum(values[offset % len(a)] for offset in [1000, 2000, 3000])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement