generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.rs
119 lines (104 loc) · 3.3 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::cmp::max;
advent_of_code::solution!(2);
enum Colour {
Blue,
Green,
Red,
}
enum Observation {
Cubes { colour: Colour, amount: usize },
EndOfHand,
}
fn parse_observations_in_game(game: &str) -> impl Iterator<Item = Observation> + '_ {
game.split(": ")
.nth(1)
.unwrap()
.split("; ")
.flat_map(|sample| {
sample
.split(", ")
.map(|observation| {
let (amount, colour) = observation.split_once(' ').unwrap();
let colour = match colour {
"green" => Colour::Green,
"blue" => Colour::Blue,
"red" => Colour::Red,
_ => panic!(),
};
Observation::Cubes {
colour,
amount: amount.parse().unwrap(),
}
})
.chain(std::iter::once(Observation::EndOfHand))
})
}
pub fn part_one(input: &str) -> Option<usize> {
Some(
input
.lines()
.enumerate()
.filter(|(_, game)| {
let mut blue = 0;
let mut green = 0;
let mut red = 0;
for observation in parse_observations_in_game(game) {
match observation {
Observation::EndOfHand => {
if blue > 14 || green > 13 || red > 12 {
return false;
}
blue = 0;
green = 0;
red = 0;
}
Observation::Cubes { amount, colour } => match colour {
Colour::Blue => blue += amount,
Colour::Green => green += amount,
Colour::Red => red += amount,
},
}
}
true
})
.map(|(index, _)| index + 1)
.sum(),
)
}
pub fn part_two(input: &str) -> Option<usize> {
Some(
input
.lines()
.map(|game| {
let mut blue = 0;
let mut green = 0;
let mut red = 0;
for observation in parse_observations_in_game(game) {
match observation {
Observation::EndOfHand => {}
Observation::Cubes { amount, colour } => match colour {
Colour::Blue => blue = max(blue, amount),
Colour::Green => green = max(green, amount),
Colour::Red => red = max(red, amount),
},
}
}
blue * green * red
})
.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));
}
}