Advertisement
hhoppe

Advent of code 2023 day 14 fast

Dec 14th, 2023
1,035
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. @numba.njit
  2. def day14_slide_left(grid):
  3.   for row in grid:
  4.     open = 0
  5.     for x, v in enumerate(row):
  6.       if v == ord('.'):
  7.         pass
  8.       elif v == ord('O'):
  9.         if open < x:
  10.           row[open], row[x] = ord('O'), ord('.')
  11.         open += 1
  12.       else:
  13.         open = x + 1
  14.  
  15.  
  16. def day14(s, *, part2=False, num=1_000_000_000):
  17.   grid = np.array([[ord(ch) for ch in line] for line in s.splitlines()], np.uint8)
  18.   grid = np.rot90(grid)  # North is now left.
  19.   grid = np.ascontiguousarray(grid)  # Layout in C-order, for tobytes().
  20.  
  21.   if not part2:
  22.     day14_slide_left(grid)
  23.  
  24.   else:
  25.     configs: dict[Any, int] = {}  # hashed_grid -> index.
  26.     period = -1
  27.     index = 0
  28.     while True:
  29.       if period < 0:
  30.         if (prev_index := configs.setdefault(grid.tobytes(), index)) != index:
  31.           period = index - prev_index
  32.           print(f'At {index=}, found cycle with {period=}.')
  33.           index = num - (num - index) % period
  34.       if index == num:
  35.         break
  36.       for _ in range(4):
  37.         day14_slide_left(grid)
  38.         grid = np.rot90(grid, -1)
  39.       index += 1
  40.  
  41.   return sum(len(grid[0]) - x for _, x in np.argwhere(grid == ord('O')))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement