1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
use regex::Regex;
static DAY: u8 = 3;
fn main() {
let input = advent::read_lines(DAY);
println!("{DAY}a: {}", sum_multiplications(&input, true));
println!("{DAY}b: {}", sum_multiplications(&input, false));
}
fn sum_multiplications(input: &[String], ignore_do: bool) -> u32 {
let re = Regex::new(r"(do)\(\)|(don't)\(\)|(mul)\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap();
let mut sum = 0;
let mut muls_enabled = true;
for line in input {
for cap in re.captures_iter(line) {
if cap.get(1).is_some() { // do
muls_enabled = true;
} else if cap.get(2).is_some() { // don't
muls_enabled = false;
} else if cap.get(3).is_some() { // mul
if ignore_do || muls_enabled {
let f1 = cap[4].parse::<u32>().unwrap();
let f2 = cap[5].parse::<u32>().unwrap();
sum += f1 * f2;
}
}
}
}
sum
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let input = [
"xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
assert_eq!(sum_multiplications(&input, true), 161);
let input = [
"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
assert_eq!(sum_multiplications(&input, false), 48);
}
}
|