Advertisement
hhoppe

Advent of code 2024 day 20 numba.njit 10 ms

Dec 20th, 2024
42
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(max(y - radius, 0), min(y + radius + 1, distance.shape[0] - 1)):
  17.         radius_x = radius - abs(y2 - y)
  18.         for x2 in range(max(x - radius_x, 0), min(x + radius_x + 1, distance.shape[1] - 1)):
  19.           d2_from_s = distance[y2, x2]
  20.           if d2_from_s >= 0:
  21.             savings = d2_from_s - d - abs(y2 - y) - abs(x2 - x)
  22.             if savings >= min_savings:
  23.               count += 1
  24.  
  25.   return count
  26.  
  27.  
  28. def day20(s, *, part2=False, min_savings=100):
  29.   grid = np.array([list(line) for line in s.splitlines()])
  30.   ((ys, xs),) = np.argwhere(grid == 'S')
  31.   ((ye, xe),) = np.argwhere(grid == 'E')
  32.   distance = np.where(grid == '#', -2, -1)
  33.   return day20_jit(distance, ys, xs, ye, xe, part2, min_savings)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement