Advertisement
hhoppe

Advent of code 2023 day 14

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