|
| 1 | +# Advent of Code 2024 - Day 11 |
| 2 | +# https://adventofcode.com/2024/day/11 |
| 3 | +# Author: Alexandre MALFREYT |
| 4 | + |
| 5 | +DEBUG = False |
| 6 | + |
| 7 | +with open('input.txt', 'r') as f: |
| 8 | + stones = [int(x) for x in f.read().strip().split(' ')] |
| 9 | + |
| 10 | +# Part 1 |
| 11 | +def simulate_blink_inplace(stones: list[int]) -> list[int]: |
| 12 | + i = 0 |
| 13 | + print(f"Simulating blink on {stones}") if DEBUG else None |
| 14 | + while i < len(stones): |
| 15 | + print(f"i={i}, stones[i]={stones[i]}") if DEBUG else None |
| 16 | + stone = stones[i] |
| 17 | + stone_str = str(stone) |
| 18 | + nb_digits = len(stone_str) |
| 19 | + |
| 20 | + if stone == 0: |
| 21 | + print(" stone is 0") if DEBUG else None |
| 22 | + stones[i] = 1 |
| 23 | + |
| 24 | + elif nb_digits % 2 == 0: |
| 25 | + print(" nb_digits is even") if DEBUG else None |
| 26 | + stones[i] = int(stone_str[:nb_digits//2]) |
| 27 | + stones.insert(i+1, int(stone_str[nb_digits//2:])) |
| 28 | + print(f" Inserted {stones[i+1]} at position {i+1}") if DEBUG else None |
| 29 | + i += 1 # Skip the next stone since we just inserted a new one |
| 30 | + |
| 31 | + else: |
| 32 | + print(" nb_digits is odd") if DEBUG else None |
| 33 | + stones[i] = stone * 2024 |
| 34 | + |
| 35 | + i += 1 |
| 36 | + |
| 37 | +def simulate_n_blinks_inplace(stones: list[int], nb_blinks: int, print_steps: bool = False) -> None: |
| 38 | + print("Initial arrangement:") if print_steps else None |
| 39 | + print(" ".join(str(x) for x in stones)) if print_steps else None |
| 40 | + print() if print_steps else None |
| 41 | + for i in range(nb_blinks): |
| 42 | + print(f"Simulating blink {i+1}") |
| 43 | + simulate_blink_inplace(stones) |
| 44 | + print(f"After {i+1} blink{'s' if i > 0 else ''}:") if print_steps else None |
| 45 | + print(" ".join(str(x) for x in stones)) if print_steps else None |
| 46 | + print() if print_steps else None |
| 47 | + |
| 48 | +simulate_n_blinks_inplace(stones, 25) |
| 49 | + |
| 50 | +print(f'Part 1 : {len(stones)}') |
| 51 | + |
| 52 | + |
| 53 | +# Part 2 |
| 54 | +total = 0 |
| 55 | + |
| 56 | +simulate_n_blinks_inplace(stones, 75-25) # 75 blinks - 25 already done |
| 57 | + |
| 58 | +print(f'Part 2 : {len(stones)}') |
| 59 | + |
| 60 | +# Examples |
| 61 | +print("--- Examples ---") |
| 62 | + |
| 63 | +stones_example1 = [0, 1, 10, 99, 999] # Example 1 |
| 64 | +stones_example2 = [125, 17] # Example 2 |
| 65 | + |
| 66 | +print("Example 1:") |
| 67 | +simulate_n_blinks_inplace(stones_example1, 1, print_steps=True) |
| 68 | +assert stones_example1 == [1, 2024, 1, 0, 9, 9, 2021976] |
| 69 | + |
| 70 | +print("Example 2:") |
| 71 | +simulate_n_blinks_inplace(stones_example2, 6, print_steps=True) |
| 72 | +assert stones_example2 == [2097446912, 14168, 4048, 2, 0, 2, 4, 40, 48, 2024, 40, 48, 80, 96, 2, 8, 6, 7, 6, 0, 3, 2] |
0 commit comments