diff --git a/2024/rust/src/day11.rs b/2024/rust/src/day11.rs index cf505da..5bd9b15 100644 --- a/2024/rust/src/day11.rs +++ b/2024/rust/src/day11.rs @@ -7,41 +7,47 @@ fn main() { } fn part1(input: &str) -> usize { - stone_blinks(input, 25) + stone_blinks_by_count(input, 25) } -fn stone_blinks(input: &str, count: usize) -> usize { - let mut stones: Vec = input +fn stone_blink(s: usize) -> Vec { + if s == 0 { + return vec![1]; + } + let ss = s.to_string(); + if ss.len() % 2 == 0 { + let mid = ss.len() / 2; + let (s1, s2) = (ss[0..mid].parse().unwrap(), ss[mid..].parse().unwrap()); + return vec![s1, s2]; + } + vec![s * 2024] +} + +fn stone_blinks_by_count(input: &str, count: usize) -> usize { + let mut stones: HashMap = input .trim() .split(" ") - .map(|s| s.parse().unwrap()) - .collect(); - let mut next_stones = vec![]; - for blink in 0..count { - println!("{blink} {}", stones.len()); - for (_i, s) in stones.iter().enumerate() { - // next_stones.push(*s) - if *s == 0 { - next_stones.push(1); - continue; + .map(|n| n.parse().unwrap()) + .fold(HashMap::new(), |mut acc, n| { + *acc.entry(n).or_default() += 1; + acc + }); + let mut next_stones: HashMap = HashMap::new(); + for _c in 0..count { + for (n, c) in &stones { + for nn in stone_blink(*n) { + *next_stones.entry(nn).or_default() += c; } - let ss = s.to_string(); - if ss.len() % 2 == 0 { - let mid = ss.len() / 2; - let (s1, s2) = (ss[0..mid].parse().unwrap(), ss[mid..].parse().unwrap()); - next_stones.push(s1); - next_stones.push(s2); - continue; - } - next_stones.push(s * 2024) } - stones = next_stones; - next_stones = vec![]; + println!("afterblink\n{stones:?}\n{next_stones:?}"); + (stones, next_stones) = (next_stones, HashMap::new()); } - stones.len() + stones.into_values().sum() } -fn part2(input: &str) -> usize {} +fn part2(input: &str) -> usize { + stone_blinks_by_count(input, 75) +} #[cfg(test)] mod tests { @@ -51,6 +57,6 @@ mod tests { fn test() { let input = r#"125 17"#; assert_eq!(part1(input), 55312); - assert_eq!(part2(input), 0); + assert_eq!(part2(input), 65601038650482); } } diff --git a/2024/rust/src/prelude.rs b/2024/rust/src/prelude.rs index dd0080f..5d7a68e 100644 --- a/2024/rust/src/prelude.rs +++ b/2024/rust/src/prelude.rs @@ -10,6 +10,7 @@ pub use std::{ iter::zip, num::{ParseFloatError, ParseIntError}, str::FromStr, + sync::{Arc, LazyLock, Mutex}, }; pub type AnyResult = std::result::Result>;