Advertisement
alexandrajay2002

Advent of Code 2024 day 11 part 2

Dec 13th, 2024
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | Source Code | 0 0
  1. from functools import cache
  2. from sys import argv
  3.  
  4. MAX_DEPTH = 75
  5.  
  6.  
  7. def parse(src):
  8.     '''Convert the input to a list of integers.'''
  9.     return [int(x) for x in src.split()]
  10.  
  11.  
  12. def count_digits(num):
  13.     '''Count the digits of num in base 10'''
  14.     total = 0
  15.     while num > 0:
  16.         total += 1
  17.         num = num // 10
  18.     return total
  19.  
  20.  
  21. @cache
  22. def expand(stone, depth=0):
  23.     '''Traverse the 'timeline' depth-first and return the number of stones
  24.       created by blinking at stone from depth to MAX_DEPTH blinks.'''
  25.     while depth < MAX_DEPTH:
  26.         if stone == 0:
  27.             stone = 1
  28.             depth += 1
  29.             continue
  30.  
  31.         digits = count_digits(stone)
  32.         if digits % 2 == 0:
  33.             mask = 10 ** (digits // 2)
  34.             left = stone // mask
  35.             right = stone % mask
  36.  
  37.             return expand(left, depth + 1) + expand(right, depth + 1)
  38.  
  39.         stone *= 2024
  40.         depth += 1
  41.  
  42.     return 1
  43.  
  44.  
  45. def main(stones):
  46.     '''The total number of stones produced after 75 blinks'''
  47.     return sum(expand(stone) for stone in stones)
  48.  
  49.  
  50. if __name__ == '__main__':
  51.     # pass the path to the puzzle input as the first argument
  52.     print(main(parse(open(argv[1]).read())))
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement