Skip to content

Commit eb9eea5

Browse files
committed
2024: Day 3 Use fold rather than stateful iterator
1 parent cb0a568 commit eb9eea5

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

2024/day03/src/main.rs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,28 +28,37 @@ fn part1(input: &Input) -> usize {
2828
.sum()
2929
}
3030

31+
#[derive(Copy, Clone, Debug)]
32+
enum Instruction {
33+
Do,
34+
Dont,
35+
Mul(usize, usize),
36+
}
37+
3138
fn part2(input: &Input) -> usize {
3239
let instr_re = Regex::new(r"(?x) (?<instr>mul|do(n't)?) \( (?:(?<a>\d{1,3}) , (?<b>\d{1,3}))? \)").unwrap();
3340

34-
let mut is_do = true;
3541
instr_re.captures_iter(&input.input)
36-
.filter_map(|m| {
42+
.map(|m| {
3743
match m.name("instr").unwrap().as_str() {
3844
"mul" => {
3945
let a: usize = m.name("a").and_then(|m| m.as_str().parse().ok()).unwrap();
4046
let b: usize = m.name("b").and_then(|m| m.as_str().parse().ok()).unwrap();
4147

42-
if is_do {
43-
return Some(a * b)
44-
};
48+
Instruction::Mul(a, b)
4549
},
46-
"do" => is_do = true,
47-
"don't" => is_do = false,
50+
"do" => Instruction::Do,
51+
"don't" => Instruction::Dont,
4852
instr => panic!("unknown instruction {instr:?}"),
4953
}
50-
51-
None
52-
}).sum()
54+
})
55+
.fold((true, 0), |(do_it, acc), instr| match instr {
56+
Instruction::Do => (true, acc),
57+
Instruction::Dont => (false, acc),
58+
Instruction::Mul(a, b) if do_it => (true, acc + a * b),
59+
_ => (do_it, acc),
60+
})
61+
.1
5362
}
5463

5564
#[derive(Debug, Clone)]

0 commit comments

Comments
 (0)