-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.rs
54 lines (43 loc) · 1.47 KB
/
day03.rs
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
51
52
53
54
use std::collections::HashSet;
use aoc_core::prelude::*;
use regex::Regex;
fn part1(input: &Input) -> isize {
let re = Regex::new(r"mul\((\d+),(\d+)\)").unwrap();
re
.captures_iter(&input.raw)
.map(|x| x.extract())
.map(|(_, [x, y])| x.parse::<isize>().unwrap() * y.parse::<isize>().unwrap())
.sum()
}
fn part2(input: &Input) -> isize {
let re = Regex::new(r"mul\((\d+),(\d+)\)|(don't|do)").unwrap();
re
.captures_iter(&input.raw)
.fold((true, 0), |(mut flag, mut result), cap| {
if let Some(word) = cap.get(3) {
flag = match &cap[3] {
"do" => true,
"don't" => false,
_ => false
};
}
if flag {
if let (Some(a), Some(b)) = (cap.get(1), cap.get(2)) {
let a: isize = a.as_str().parse().unwrap();
let b: isize = b.as_str().parse().unwrap();
result += a.checked_mul(b).unwrap();
}
}
(flag, result)
})
.1
}
runner!();
#[cfg(test)]
#[test]
fn test() {
let input = Input::new("xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))".to_string());
assert_eq!(part1(&input), 161, "Part 1");
let input = Input::new("xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))".to_string());
assert_eq!(part2(&input), 48, "Part 2");
}