|
| 1 | +use itertools::Itertools; |
| 2 | +use std::collections::HashMap; |
| 3 | + |
| 4 | +advent_of_code::solution!(11); |
| 5 | + |
| 6 | +fn blink(stone: u64, iterations_left: usize, memo: &mut HashMap<(u64, usize), u64>) -> u64 { |
| 7 | + if iterations_left == 0 { |
| 8 | + return 1; |
| 9 | + } |
| 10 | + if let Some(cached_value) = memo.get(&(stone, iterations_left)) { |
| 11 | + return *cached_value; |
| 12 | + } |
| 13 | + |
| 14 | + let (first_half, second_half) = blink_stone(stone); |
| 15 | + let mut sum = blink(first_half, iterations_left - 1, memo); |
| 16 | + if let Some(second_half) = second_half { sum += blink(second_half, iterations_left - 1, memo); } |
| 17 | + |
| 18 | + memo.insert((stone, iterations_left), sum); |
| 19 | + |
| 20 | + sum |
| 21 | +} |
| 22 | + |
| 23 | +fn blink_stone(stone: u64) -> (u64, Option<u64>) { |
| 24 | + if stone == 0 { |
| 25 | + return (1, None); |
| 26 | + } |
| 27 | + |
| 28 | + let digits = stone.ilog10() + 1; |
| 29 | + if digits % 2 != 0 { |
| 30 | + return (stone * 2024, None) |
| 31 | + } |
| 32 | + let divisor = 10u64.pow(digits / 2); |
| 33 | + let first_half = stone / divisor; |
| 34 | + let second_half = stone % divisor; |
| 35 | + (first_half, Some(second_half)) |
| 36 | +} |
| 37 | + |
| 38 | +pub fn part_one(input: &str) -> Option<u64> { |
| 39 | + let stones = input.split_ascii_whitespace().map(|number| number.parse::<u64>().unwrap()).collect_vec(); |
| 40 | + let mut memo = HashMap::new(); |
| 41 | + Some(stones.iter().map(|stone| blink(*stone, 25, &mut memo)).sum()) |
| 42 | +} |
| 43 | + |
| 44 | +pub fn part_two(input: &str) -> Option<u64> { |
| 45 | + let stones = input.split_ascii_whitespace().map(|number| number.parse::<u64>().unwrap()).collect_vec(); |
| 46 | + let mut memo = HashMap::new(); |
| 47 | + Some(stones.iter().map(|stone| blink(*stone, 75, &mut memo)).sum()) |
| 48 | +} |
| 49 | + |
| 50 | +#[cfg(test)] |
| 51 | +mod tests { |
| 52 | + use super::*; |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_part_one() { |
| 56 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 57 | + assert_eq!(result, Some(55312)); |
| 58 | + } |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn test_part_two() { |
| 62 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 63 | + assert_eq!(result, Some(65601038650482)); |
| 64 | + } |
| 65 | +} |
0 commit comments