Skip to content

Commit 5c054d9

Browse files
committed
2024 day 11
1 parent 485d01b commit 5c054d9

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

crates/year2024/src/day11.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use std::collections::HashMap;
2+
use utils::prelude::*;
3+
4+
/// Counting dividing stones.
5+
#[derive(Clone, Debug)]
6+
pub struct Day11 {
7+
stones: HashMap<u64, u64>,
8+
}
9+
10+
impl Day11 {
11+
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
12+
let mut stones = HashMap::new();
13+
for v in parser::u64().repeat(b' ', 1).parse_complete(input)? {
14+
*stones.entry(v).or_insert(0) += 1;
15+
}
16+
Ok(Self { stones })
17+
}
18+
19+
#[must_use]
20+
pub fn part1(&self) -> u64 {
21+
self.blink(25)
22+
}
23+
24+
#[must_use]
25+
pub fn part2(&self) -> u64 {
26+
self.blink(75)
27+
}
28+
29+
fn blink(&self, times: u32) -> u64 {
30+
let mut stones = self.stones.clone();
31+
let mut next = HashMap::new();
32+
for _ in 0..times {
33+
for (&x, &c) in stones.iter() {
34+
if x == 0 {
35+
next.entry(1).and_modify(|v| *v += c).or_insert(c);
36+
} else {
37+
let log = x.ilog10() + 1;
38+
if log % 2 == 0 {
39+
let pow = 10u64.pow(log / 2);
40+
next.entry(x / pow).and_modify(|v| *v += c).or_insert(c);
41+
next.entry(x % pow).and_modify(|v| *v += c).or_insert(c);
42+
} else {
43+
next.entry(x * 2024).and_modify(|v| *v += c).or_insert(c);
44+
}
45+
}
46+
}
47+
48+
(stones, next) = (next, stones);
49+
next.clear();
50+
}
51+
stones.values().sum()
52+
}
53+
}
54+
55+
examples!(Day11 -> (u64, u64) [
56+
{input: "125 17", part1: 55312},
57+
]);

crates/year2024/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ utils::year!(2024 => year2024, ${
1212
8 => day08::Day08,
1313
9 => day09::Day09<'_>,
1414
10 => day10::Day10,
15+
11 => day11::Day11,
1516
});

0 commit comments

Comments
 (0)