This repository was archived by the owner on Feb 26, 2024. It is now read-only.
generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.rs
113 lines (91 loc) · 2.9 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
advent_of_code::solution!(2);
/* -------------------------------------------------------------------------- */
struct Game {
id: u32,
draw: Vec<Draw>,
}
#[derive(Default, Clone, Copy)]
struct Draw {
red: u32,
green: u32,
blue: u32,
}
fn parse_input(input: &str) -> Vec<Game> {
input
.lines()
.map(|line| {
let (head, data) = line.split_once(':').unwrap();
let id = head.strip_prefix("Game ").unwrap().parse().unwrap();
let draw = data
.split(';')
.map(|draw| {
let mut red = 0;
let mut green = 0;
let mut blue = 0;
draw.split(',').for_each(|draw| {
let (count, color) = draw.trim().split_once(' ').unwrap();
let count: u32 = count.parse().unwrap();
match color {
"red" => red += count,
"green" => green += count,
"blue" => blue += count,
_ => unreachable!(),
}
});
Draw { red, green, blue }
})
.collect();
Game { id, draw }
})
.collect()
}
/* -------------------------------------------------------------------------- */
pub fn part_one(input: &str) -> Option<u32> {
let games = parse_input(input);
let result = games
.into_iter()
.filter(|game| {
game.draw
.iter()
.copied()
.all(|Draw { red, green, blue }| red <= 12 && green <= 13 && blue <= 14)
})
.map(|game| game.id)
.sum();
Some(result)
}
/* -------------------------------------------------------------------------- */
pub fn part_two(input: &str) -> Option<u32> {
let games = parse_input(input);
let result = games
.into_iter()
.map(|game| {
let minimum_colors = game
.draw
.into_iter()
.reduce(|acc, e| Draw {
red: acc.red.max(e.red),
green: acc.green.max(e.green),
blue: acc.blue.max(e.blue),
})
.unwrap_or_default();
minimum_colors.red * minimum_colors.green * minimum_colors.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));
}
}