Advertisement
hhoppe

Advent of code 2024 day 10 numba fastest

Dec 10th, 2024
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. @numba.njit
  2. def day10_jit(grid, part2):
  3.   neighbors = (0, -1), (0, 1), (-1, 0), (1, 0)
  4.   total = 0
  5.  
  6.   if not part2:
  7.     for y0 in range(1, grid.shape[0] - 1):
  8.       for x0 in range(1, grid.shape[1] - 1):
  9.         if grid[y0, x0] == 0:
  10.           active = {(y0, x0)}  # Set of positions reached after `dist` moves.
  11.           for dist in range(1, 10):
  12.             active2 = set()
  13.             for y, x in active:
  14.               for dy, dx in neighbors:
  15.                 y2, x2 = y + dy, x + dx
  16.                 if grid[y2, x2] == dist:
  17.                   active2.add((y2, x2))
  18.             active = active2
  19.           total += len(active)
  20.  
  21.   else:
  22.     a = np.empty_like(grid)
  23.     for y in range(1, grid.shape[0] - 1):
  24.       for x in range(1, grid.shape[1] - 1):
  25.         if grid[y, x] == 9:
  26.           a[y, x] = 1
  27.     for dist in range(8, -1, -1):
  28.       for y in range(1, grid.shape[0] - 1):
  29.         for x in range(1, grid.shape[1] - 1):
  30.           if grid[y, x] == dist:
  31.             count = 0
  32.             for dy, dx in neighbors:
  33.               y2, x2 = y + dy, x + dx
  34.               if grid[y2, x2] == dist + 1:
  35.                 count += a[y2, x2]
  36.             a[y, x] = count
  37.     for y in range(1, grid.shape[0] - 1):
  38.       for x in range(1, grid.shape[1] - 1):
  39.         if grid[y, x] == 0:
  40.           total += a[y, x]
  41.  
  42.   return total
  43.  
  44.  
  45. def day10(s, part2=False):
  46.   grid = np.array([list(line) for line in s.splitlines()], int)
  47.   grid = np.pad(grid, 1, constant_values=-1)
  48.   return day10_jit(grid, part2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement