Skip to content

Commit 5aa4299

Browse files
committed
2025 day 3
1 parent 4ab542f commit 5aa4299

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

crates/year2025/src/day03.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
use utils::prelude::*;
2+
3+
/// Finding the maximum number from ordered digits.
4+
#[derive(Clone, Debug)]
5+
pub struct Day03<'a> {
6+
lines: Vec<&'a str>,
7+
}
8+
9+
impl<'a> Day03<'a> {
10+
pub fn new(input: &'a str, _: InputType) -> Result<Self, InputError> {
11+
let lines: Vec<&str> = input.lines().collect();
12+
for &l in &lines {
13+
if let Some(b) = l.bytes().find(|x| !x.is_ascii_digit()) {
14+
return Err(InputError::new(input, b as char, "expected digit"));
15+
}
16+
if l.len() < 12 {
17+
return Err(InputError::new(input, l, "expected at least 12 digits"));
18+
}
19+
}
20+
Ok(Self { lines })
21+
}
22+
23+
#[must_use]
24+
pub fn part1(&self) -> u64 {
25+
self.output_joltage::<2>()
26+
}
27+
28+
#[must_use]
29+
pub fn part2(&self) -> u64 {
30+
self.output_joltage::<12>()
31+
}
32+
33+
fn output_joltage<const N: usize>(&self) -> u64 {
34+
let mut sum = 0;
35+
for l in &self.lines {
36+
let mut nums = [0u8; N];
37+
let (first, last) = l.as_bytes().split_last_chunk::<N>().unwrap();
38+
39+
for &b in first {
40+
for j in 0..N {
41+
let x = b - b'0';
42+
if x > nums[j] {
43+
nums[j] = x;
44+
nums[j + 1..].fill(0);
45+
break;
46+
}
47+
}
48+
}
49+
50+
for (i, &b) in last.iter().enumerate() {
51+
for j in i..N {
52+
let x = b - b'0';
53+
if x > nums[j] {
54+
nums[j] = x;
55+
nums[j + 1..].fill(0);
56+
break;
57+
}
58+
}
59+
}
60+
61+
sum += nums.iter().fold(0, |acc, &x| acc * 10 + x as u64);
62+
}
63+
sum
64+
}
65+
}
66+
67+
examples!(Day03<'_> -> (u64, u64) [
68+
{
69+
input: "987654321111111\n811111111111119\n234234234234278\n818181911112111",
70+
part1: 357,
71+
part2: 3121910778619,
72+
},
73+
]);

crates/year2025/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
utils::year!(2025 => year2025, ${
55
1 => day01::Day01,
66
2 => day02::Day02,
7+
3 => day03::Day03<'_>,
78
});

0 commit comments

Comments
 (0)