generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.rs
133 lines (111 loc) · 3.29 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::cmp::max;
use itertools::Itertools;
advent_of_code::solution!(2);
struct Round {
red: u32,
green: u32,
blue: u32,
}
impl Round {
fn zeros() -> Round {
Self {
red: 0,
green: 0,
blue: 0,
}
}
}
struct Game {
id: u32,
rounds: Vec<Round>,
}
impl Game {
fn from_str(s: &str) -> Self {
let mut parts = s.split(':');
let game = parts
.next()
.expect("Always a game label")
.split_ascii_whitespace()
.nth(1)
.expect("Always a game id")
.parse()
.expect("Always an integer");
let rounds = parts.next().expect("Always rounds").trim().split("; ");
let rounds = rounds
.map(|round| {
let mut red = 0;
let mut green = 0;
let mut blue = 0;
round.split(", ").for_each(|cube_combo| {
let mut round_parts = cube_combo.split_ascii_whitespace();
let num: u32 = round_parts
.next()
.expect("Always a number")
.parse()
.expect("Always integer");
let color = round_parts.next().expect("Always a color");
match color {
"red" => red += num,
"green" => green += num,
"blue" => blue += num,
_ => {
panic!("Invalid color {color}!")
}
}
});
Round { red, green, blue }
})
.collect_vec();
Self { id: game, rounds }
}
}
pub fn part_one(input: &str) -> Option<u32> {
let games = input.lines().map(Game::from_str);
Some(
games
.map(|game| {
let possible = game
.rounds
.iter()
.any(|round| round.red > 12 || round.green > 13 || round.blue > 14);
if !possible {
game.id
} else {
0
}
})
.sum(),
)
}
pub fn part_two(input: &str) -> Option<u32> {
let games = input.lines().map(Game::from_str);
Some(
games
.map(|game| {
let min_game_config =
game.rounds
.iter()
.fold(Round::zeros(), |min_cubes, round| Round {
red: max(min_cubes.red, round.red),
green: max(min_cubes.green, round.green),
blue: max(min_cubes.blue, round.blue),
});
min_game_config.red * min_game_config.green * min_game_config.blue
})
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples/part1", DAY));
assert_eq!(result, Some(8));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples/part2", DAY));
assert_eq!(result, Some(2286));
}
}