Advertisement
hhoppe

Advent of code 2024 day 20 jit symmetrized 5 ms

Dec 20th, 2024 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. @numba.njit
  2. def day20_jit(distance, ys, xs, ye, xe, part2, min_savings):
  3.   d, y, x = 0, ys, xs
  4.   distance[y, x] = d
  5.   while (y, x) != (ye, xe):
  6.     for y, x in ((y, x - 1), (y, x + 1), (y - 1, x), (y + 1, x)):
  7.       if distance[y, x] == -1:
  8.         break
  9.     d += 1
  10.     distance[y, x] = d
  11.  
  12.   radius = 20 if part2 else 2
  13.   count = 0
  14.   for (y, x), d in np.ndenumerate(distance):
  15.     if d >= 0:
  16.       for y2 in range(y, min(y + radius + 1, distance.shape[0] - 1)):
  17.         radius_x = radius - abs(y2 - y)
  18.         xt = x - radius_x if y2 > y else x + 1
  19.         for x2 in range(max(xt, 0), min(x + radius_x + 1, distance.shape[1] - 1)):
  20.           d2 = distance[y2, x2]
  21.           if d2 >= 0:
  22.             savings = abs(d2 - d) - abs(y2 - y) - abs(x2 - x)
  23.             if savings >= min_savings:
  24.               count += 1
  25.  
  26.   return count
  27.  
  28.  
  29. def day20(s, *, part2=False, min_savings=100):
  30.   grid = np.array([list(line) for line in s.splitlines()])
  31.   ((ys, xs),) = np.argwhere(grid == 'S')
  32.   ((ye, xe),) = np.argwhere(grid == 'E')
  33.   distance = np.where(grid == '#', -2, -1)
  34.   return day20_jit(distance, ys, xs, ye, xe, part2, min_savings)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement