JonathanGupton

Advent of Code 2024 - Day 11 - Python

Dec 11th, 2024
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. from collections import deque
  2. from functools import cache
  3. from typing import Sequence
  4.  
  5.  
  6. def parse_data(fp: str) -> list[int]:
  7.     with open(fp, "r") as f:
  8.         return [*map(int, f.read().strip().split())]
  9.  
  10.  
  11. def get_evolved_stones_count(stones: Sequence[int], n_iterations: int) -> int:
  12.  
  13.     @cache
  14.     def count_evolved_stones(stone: int, n_iterations: int) -> int:
  15.         if n_iterations == 0:
  16.             return 1
  17.         else:
  18.             total = 0
  19.             if stone == 0:
  20.                 total += count_evolved_stones(1, n_iterations - 1)
  21.             elif len(str(stone)) % 2 == 0:
  22.                 num_str = str(stone)
  23.                 new_num_lens = len(num_str)//2
  24.                 total += count_evolved_stones(int(num_str[new_num_lens:]), n_iterations - 1)
  25.                 total += count_evolved_stones(int(num_str[:new_num_lens]), n_iterations - 1)
  26.             else:
  27.                 total += count_evolved_stones(stone * 2024, n_iterations - 1)
  28.             return total
  29.  
  30.     q = deque([(stone, n_iterations) for stone in stones])
  31.     count = 0
  32.     while q:
  33.         next_val = q.popleft()
  34.         count += count_evolved_stones(*next_val)
  35.     return count
  36.  
  37.  
  38. def example_a():
  39.     fp = "./example/day11-example02.txt"
  40.     data = parse_data(fp)
  41.     count = get_evolved_stones_count(data, 2)
  42.     print(count, "= 4")
  43.  
  44.     fp = "./example/day11-example02.txt"
  45.     data = parse_data(fp)
  46.     count = get_evolved_stones_count(data, 3)
  47.     print(count, "= 5")
  48.  
  49.     fp = "./example/day11-example02.txt"
  50.     data = parse_data(fp)
  51.     count = get_evolved_stones_count(data, 25)
  52.     print(count,"= 55312")
  53.  
  54.  
  55. def part_a():
  56.     fp = "./data/day11.txt"
  57.     data = parse_data(fp)
  58.     count = get_evolved_stones_count(data, 25)
  59.     print(count)
  60.  
  61. def part_b():
  62.     fp = "./data/day11.txt"
  63.     data = parse_data(fp)
  64.     count = get_evolved_stones_count(data, 75)
  65.     print(count)
  66.  
  67.  
  68. if __name__ == '__main__':
  69.     example_a()
  70.     part_a()
  71.     part_b()
Advertisement
Add Comment
Please, Sign In to add comment