|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use crate::solution::{AocError, Solution}; |
| 4 | + |
| 5 | +type Cache = HashMap<u64, HashMap<usize, usize>>; |
| 6 | + |
| 7 | +fn parse(input: &str) -> Result<Vec<u64>, AocError> { |
| 8 | + input |
| 9 | + .split_ascii_whitespace() |
| 10 | + .map(|number| { |
| 11 | + number |
| 12 | + .parse::<u64>() |
| 13 | + .map_err(|err| AocError::parse(number, err)) |
| 14 | + }) |
| 15 | + .collect() |
| 16 | +} |
| 17 | + |
| 18 | +fn split(stone: u64) -> Option<(u64, u64)> { |
| 19 | + let digits = stone.ilog10() + 1; |
| 20 | + if digits % 2 != 0 { |
| 21 | + return None; |
| 22 | + } |
| 23 | + |
| 24 | + let divisor = 10u64.pow(digits / 2); |
| 25 | + let left = stone / divisor; |
| 26 | + let right = stone % divisor; |
| 27 | + |
| 28 | + Some((left, right)) |
| 29 | +} |
| 30 | + |
| 31 | +fn simulate(stone: u64, steps: usize, cache: &mut Cache) -> usize { |
| 32 | + if steps == 0 { |
| 33 | + return 1; |
| 34 | + } |
| 35 | + |
| 36 | + if let Some(&count) = cache.get(&stone).and_then(|counts| counts.get(&steps)) { |
| 37 | + return count; |
| 38 | + } |
| 39 | + |
| 40 | + let count = if stone == 0 { |
| 41 | + simulate(1, steps - 1, cache) |
| 42 | + } else if let Some((left, right)) = split(stone) { |
| 43 | + simulate(left, steps - 1, cache) + simulate(right, steps - 1, cache) |
| 44 | + } else { |
| 45 | + simulate(stone * 2024, steps - 1, cache) |
| 46 | + }; |
| 47 | + |
| 48 | + cache.entry(stone).or_default().insert(steps, count); |
| 49 | + |
| 50 | + count |
| 51 | +} |
| 52 | + |
| 53 | +pub struct Day11; |
| 54 | +impl Solution for Day11 { |
| 55 | + type A = usize; |
| 56 | + type B = usize; |
| 57 | + |
| 58 | + fn default_input(&self) -> &'static str { |
| 59 | + include_str!("../../../inputs/2024/day11.txt") |
| 60 | + } |
| 61 | + |
| 62 | + fn part_1(&self, input: &str) -> Result<usize, AocError> { |
| 63 | + let stones = parse(input)?; |
| 64 | + let mut cache = HashMap::new(); |
| 65 | + |
| 66 | + let count = stones |
| 67 | + .into_iter() |
| 68 | + .map(|stone| simulate(stone, 25, &mut cache)) |
| 69 | + .sum(); |
| 70 | + |
| 71 | + Ok(count) |
| 72 | + } |
| 73 | + |
| 74 | + fn part_2(&self, input: &str) -> Result<usize, AocError> { |
| 75 | + let stones = parse(input)?; |
| 76 | + let mut cache = HashMap::new(); |
| 77 | + |
| 78 | + let count = stones |
| 79 | + .into_iter() |
| 80 | + .map(|stone| simulate(stone, 75, &mut cache)) |
| 81 | + .sum(); |
| 82 | + |
| 83 | + Ok(count) |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +#[cfg(test)] |
| 88 | +mod tests { |
| 89 | + use super::*; |
| 90 | + |
| 91 | + #[test] |
| 92 | + fn it_solves_part1_example_1() { |
| 93 | + assert_eq!(Day11.part_1("125 17"), Ok(55312)); |
| 94 | + } |
| 95 | +} |
0 commit comments