Guest User

Untitled

a guest
Dec 14th, 2023
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. from copy import deepcopy
  2. from functools import cache
  3.  
  4. from tqdm import tqdm
  5.  
  6.  
  7. def parse_input(filedata):
  8.     return filedata.splitlines()
  9.  
  10.  
  11. def solve1(inputs):
  12.     grid = list(map(list, inputs))
  13.  
  14.     def _drop_stone(y, x):
  15.         ny = y
  16.         while ny - 1 >= 0 and grid[ny - 1][x] == ".":
  17.             ny -= 1
  18.         grid[ny][x], grid[y][x] = grid[y][x], grid[ny][x]
  19.  
  20.     for y in range(len(grid)):
  21.         for x in range(len(grid[0])):
  22.             if grid[y][x] == "O":
  23.                 _drop_stone(y, x)
  24.  
  25.     return sum(value * row.count("O") for value, row in enumerate(grid[::-1], start=1))
  26.  
  27.  
  28. def solve2(inputs):
  29.     @cache
  30.     def _rotate_right(grid):
  31.         return tuple(map(lambda x: "".join(x), zip(*grid[::-1])))
  32.  
  33.     grid = tuple(inputs)
  34.     for _ in range(3):
  35.         grid = _rotate_right(grid)
  36.  
  37.     @cache
  38.     def _drop_row(row: str):
  39.         return "#".join("".join(sorted(x, reverse=True)) for x in row.split("#"))
  40.  
  41.     @cache
  42.     def _drop_stones(grid):
  43.         return tuple(map(_drop_row, grid))
  44.  
  45.     @cache
  46.     def _cycle(grid):
  47.         for _ in range(4):
  48.             grid = _drop_stones(grid)
  49.             grid = _rotate_right(grid)
  50.         return grid
  51.  
  52.     for _ in tqdm(range(1_000_000_000), dynamic_ncols=True):
  53.         grid = _cycle(grid)
  54.  
  55.     grid = _rotate_right(grid)
  56.     return sum(value * row.count("O") for value, row in enumerate(grid[::-1], start=1))
  57.  
  58.  
  59. def main():
  60.     with open("data/input.txt") as f:
  61.         inputs = parse_input(f.read())
  62.  
  63.     print(f"Solution 1: {solve1(deepcopy(inputs))}")
  64.     print(f"Solution 2: {solve2(deepcopy(inputs))}")
  65.  
  66.  
  67. if __name__ == "__main__":
  68.     main()
  69.  
Advertisement
Add Comment
Please, Sign In to add comment