Skip to content

Commit 184805a

Browse files
committed
2024: Add more elegant concat implementation for Day 7
1 parent 043b603 commit 184805a

File tree

1 file changed

+37
-25
lines changed

1 file changed

+37
-25
lines changed

2024/day07/src/main.rs

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,43 @@ fn main() {
1616
println!("Part 2: {}", part2(&input));
1717
}
1818

19+
#[derive(Debug, Copy, Clone)]
20+
enum Op {
21+
Add,
22+
Mul,
23+
Concat,
24+
}
25+
26+
impl Op {
27+
fn apply(&self, left: u64, right: u64) -> u64 {
28+
match self {
29+
Op::Add => left + right,
30+
Op::Mul => left * right,
31+
Op::Concat => left * right.next_multiple_of(10) + right,
32+
}
33+
}
34+
}
35+
1936
fn part1(input: &Input) -> u64 {
2037
let mut sum = 0;
2138

2239
for (result, values) in input.values.iter() {
40+
let result = *result;
41+
2342
let mut edge = vec![(1, values[0])];
2443
while let Some((n, x)) = edge.pop() {
2544
if n == values.len() {
26-
if x == *result {
27-
sum += *result;
45+
if x == result {
46+
// solved!
47+
sum += result;
2848
break;
2949
}
3050
} else {
31-
let add = x + values[n];
32-
if add <= *result {
33-
edge.push((n + 1, add));
34-
}
35-
36-
let mul = x * values[n];
37-
if mul <= *result {
38-
edge.push((n + 1, mul));
51+
for op in [Op::Add, Op::Mul] {
52+
let val = op.apply(x, values[n]);
53+
if val <= result {
54+
edge.push((n + 1, val));
55+
}
3956
}
4057
}
4158
}
@@ -48,27 +65,22 @@ fn part2(input: &Input) -> u64 {
4865
let mut sum = 0;
4966

5067
for (result, values) in input.values.iter() {
68+
let result = *result;
69+
5170
let mut edge = vec![(1, values[0])];
5271
while let Some((n, x)) = edge.pop() {
5372
if n == values.len() {
54-
if x == *result {
55-
sum += *result;
73+
// solved!
74+
if x == result {
75+
sum += result;
5676
break;
5777
}
5878
} else {
59-
let add = x + values[n];
60-
if add <= *result {
61-
edge.push((n + 1, add));
62-
}
63-
64-
let mul = x * values[n];
65-
if mul <= *result {
66-
edge.push((n + 1, mul));
67-
}
68-
69-
let concat = format!("{}{}", x, values[n]).parse().unwrap();
70-
if concat <= *result {
71-
edge.push((n + 1, concat));
79+
for op in [Op::Add, Op::Mul, Op::Concat] {
80+
let val = op.apply(x, values[n]);
81+
if val <= result {
82+
edge.push((n + 1, val));
83+
}
7284
}
7385
}
7486
}

0 commit comments

Comments
 (0)