generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.rs
97 lines (78 loc) · 2.18 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
advent_of_code::solution!(2);
use advent_of_code::maneatingape::parse::*;
struct Game {
id: u32,
sets: Vec<Set>,
}
#[derive(Default)]
struct Set {
red: u32,
green: u32,
blue: u32,
}
impl From<&str> for Set {
fn from(item: &str) -> Self {
let mut result = Set::default();
item.split(", ")
.filter_map(|x| x.split_once(' '))
.for_each(|(n, color)| match color.as_bytes()[0] {
b'r' => result.red = n.unsigned(),
b'g' => result.green = n.unsigned(),
b'b' => result.blue = n.unsigned(),
_ => unreachable!(),
});
result
}
}
impl From<&str> for Game {
fn from(item: &str) -> Self {
let (game_id, game_data) = item.split_once(": ").unwrap();
let id = game_id.unsigned();
let sets = game_data.split("; ").map(Set::from).collect();
Game { id, sets }
}
}
fn parse_data(input: &str) -> Vec<Game> {
input.lines().map(Game::from).collect()
}
pub fn part_one(input: &str) -> Option<u32> {
let data = parse_data(input);
let result = data
.into_iter()
.filter(|game| {
!game
.sets
.iter()
.any(|set| set.red > 12 || set.green > 13 || set.blue > 14)
})
.map(|game| game.id)
.sum();
Some(result)
}
pub fn part_two(input: &str) -> Option<u32> {
let data = parse_data(input);
let result = data
.into_iter()
.map(|game| Set {
red: game.sets.iter().map(|x| x.red).max().unwrap(),
green: game.sets.iter().map(|x| x.green).max().unwrap(),
blue: game.sets.iter().map(|x| x.blue).max().unwrap(),
})
.map(|set| set.red * set.green * set.blue)
.sum();
Some(result)
}
#[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));
}
}