generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02.rs
74 lines (68 loc) · 2.52 KB
/
02.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
advent_of_code::solution!(2);
use regex::Regex;
pub fn part_one(input: &str) -> Option<u32> {
Some(
input
.lines()
.filter_map(|line| {
let game_re = Regex::new(r"^Game (\d+):").unwrap();
let red_re = Regex::new(r" (\d+) red").unwrap();
let green_re = Regex::new(r" (\d+) green").unwrap();
let blue_re = Regex::new(r" (\d+) blue").unwrap();
let game_id = game_re.captures(line).expect("Expected game_id to exist")[1]
.parse::<u32>()
.expect("Expect game_id to be an int");
let has_over_max = |re: Regex, max: u32| {
re.captures_iter(line)
.filter(|c| c[1].parse::<u32>().expect("Color capture should be int") > max)
.count()
!= 0
};
let reds_over_max = has_over_max(red_re, 12);
let greens_over_max = has_over_max(green_re, 13);
let blues_over_max = has_over_max(blue_re, 14);
if reds_over_max || greens_over_max || blues_over_max {
None
} else {
Some(game_id)
}
})
.sum(),
)
}
pub fn part_two(input: &str) -> Option<u32> {
Some(
input
.lines()
.map(|line| {
let red_re = Regex::new(r" (\d+) red").unwrap();
let green_re = Regex::new(r" (\d+) green").unwrap();
let blue_re = Regex::new(r" (\d+) blue").unwrap();
let largest_capture = |re: Regex| {
re.captures_iter(line)
.map(|c| c[1].parse::<u32>().expect("Color capture should be int"))
.reduce(|acc, e| if e > acc { e } else { acc })
.unwrap()
};
let reds = largest_capture(red_re);
let greens = largest_capture(green_re);
let blues = largest_capture(blue_re);
reds * greens * blues
})
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(8));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(2286));
}
}