From 925a735a8b16f9ad6e579f0d9c6808105a5d0fa2 Mon Sep 17 00:00:00 2001 From: Rh4096 Date: Wed, 11 Dec 2024 13:48:07 +0700 Subject: [PATCH] day 11 --- src/main.rs | 1 + src/solutions/day_11.rs | 60 ++++++++++++++++++++++++++++++++++++++--- src/solutions/mod.rs | 5 ++-- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3c28fb0..f3b65de 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,6 +32,7 @@ fn main() -> Result<()> { 8 => AocDayEightSolution, 9 => AocDayNineSolution, 10 => AocDayTenSolution, + 11 => AocDayElevenSolution, }; Ok(()) diff --git a/src/solutions/day_11.rs b/src/solutions/day_11.rs index 3279298..bc5b02a 100644 --- a/src/solutions/day_11.rs +++ b/src/solutions/day_11.rs @@ -1,8 +1,58 @@ -use std::{fs::read_to_string, path::Path}; +use std::{collections::HashMap, fs::read_to_string, path::Path}; use super::AocSolution; use crate::utils::Result; +struct Stones { + stones: Vec, +} + +impl Stones { + fn new(src: &str) -> Self { + Self { + stones: src + .split_whitespace() + .filter_map(|num| num.parse().ok()) + .collect(), + } + } + + fn blinks(&self, cnt: u8) -> u64 { + fn _inner(cache: &mut HashMap<(u64, u8), u64>, stone: u64, cnt: u8) -> u64 { + if cnt == 0 { + return 1; + } + + if let Some(&val) = cache.get(&(stone, cnt)) { + return val; + } + + let next = match stone { + 0 => _inner(cache, 1, cnt - 1), + n => { + let digits = n.ilog10() + 1; + if digits % 2 == 0 { + let pow = 10u64.pow(digits / 2); + _inner(cache, stone / pow, cnt - 1) + _inner(cache, stone % pow, cnt - 1) + } else { + _inner(cache, stone * 2024, cnt - 1) + } + } + }; + + cache.insert((stone, cnt), next); + next + } + + let mut cache = HashMap::new(); + self.stones + .iter() + .map(|&x| _inner(&mut cache, x, cnt)) + .sum() + } +} + +#[derive(Clone, Copy)] pub struct AocDayElevenSolution; impl AocSolution for AocDayElevenSolution { @@ -11,15 +61,17 @@ impl AocSolution for AocDayElevenSolution { fn get_input(&self, path: Option<&Path>) -> Result { Ok(match path { Some(p) => read_to_string(p)?, - None => read_to_string("./input/day_day_11.txt")?, + None => read_to_string("./input/day_11.txt")?, }) } fn part_one(&self, input: &str) -> Result { - todo!() + let stones = Stones::new(input); + Ok(stones.blinks(25)) } fn part_two(&self, input: &str) -> Result { - todo!() + let stones = Stones::new(input); + Ok(stones.blinks(75)) } } diff --git a/src/solutions/mod.rs b/src/solutions/mod.rs index daa2f4f..73fcae5 100644 --- a/src/solutions/mod.rs +++ b/src/solutions/mod.rs @@ -9,9 +9,8 @@ macro_rules! define_solution { } define_solution!( - day_1, day_2, day_3, day_4, day_5, day_6, day_7, day_8, day_9, - day_10, - // day_11, + day_1, day_2, day_3, day_4, day_5, day_6, day_7, day_8, day_9, day_10, + day_11, // day_12, // day_13, // day_14,