|
| 1 | +//! # Plutonian Pebbles |
| 2 | +//! |
| 3 | +//! Each stone is independent and does not affect its neighbours. This means that we can |
| 4 | +//! recursively split each stone, skipping trillions of calculations by memoizing the count for |
| 5 | +//! each `(stone, blinks)` tuple. |
| 6 | +//! |
| 7 | +//! Interestingly the number of distinct stones is not too large, about 5000 for part two. |
| 8 | +use crate::util::hash::*; |
| 9 | +use crate::util::parse::*; |
| 10 | + |
| 11 | +pub fn parse(input: &str) -> Vec<u64> { |
| 12 | + input.iter_unsigned().collect() |
| 13 | +} |
| 14 | + |
| 15 | +pub fn part1(input: &[u64]) -> u64 { |
| 16 | + let cache = &mut FastMap::with_capacity(5_000); |
| 17 | + input.iter().map(|&stone| count(cache, stone, 25)).sum() |
| 18 | +} |
| 19 | + |
| 20 | +pub fn part2(input: &[u64]) -> u64 { |
| 21 | + let cache = &mut FastMap::with_capacity(150_000); |
| 22 | + input.iter().map(|&stone| count(cache, stone, 75)).sum() |
| 23 | +} |
| 24 | + |
| 25 | +fn count(cache: &mut FastMap<(u64, u64), u64>, stone: u64, blinks: u64) -> u64 { |
| 26 | + if blinks == 1 { |
| 27 | + if stone == 0 { |
| 28 | + return 1; |
| 29 | + } |
| 30 | + let digits = stone.ilog10() + 1; |
| 31 | + return if digits % 2 == 0 { 2 } else { 1 }; |
| 32 | + } |
| 33 | + |
| 34 | + let key = (stone, blinks); |
| 35 | + if let Some(&value) = cache.get(&key) { |
| 36 | + return value; |
| 37 | + } |
| 38 | + |
| 39 | + let next = if stone == 0 { |
| 40 | + count(cache, 1, blinks - 1) |
| 41 | + } else { |
| 42 | + let digits = stone.ilog10() + 1; |
| 43 | + if digits % 2 == 0 { |
| 44 | + let power = 10_u64.pow(digits / 2); |
| 45 | + count(cache, stone / power, blinks - 1) + count(cache, stone % power, blinks - 1) |
| 46 | + } else { |
| 47 | + count(cache, stone * 2024, blinks - 1) |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + cache.insert(key, next); |
| 52 | + next |
| 53 | +} |
0 commit comments