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
|
use nom::{
bytes::complete::tag,
character::complete::{alpha1, line_ending, u32 as nom_u32},
combinator::map,
multi::separated_list1,
sequence::tuple,
IResult,
};
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let input = fs::read_to_string("inputs/day_2.txt")?;
let parsed = Games::parser(&input).unwrap().1;
let max_pull = Pull {
red: 12,
green: 13,
blue: 14,
};
dbg!(&parsed.valid_game_id_sum(&max_pull));
dbg!(&parsed.power_sum());
Ok(())
}
#[derive(Debug)]
struct Games(Vec<Game>);
#[derive(Debug)]
struct Game {
id: u32,
pulls: Vec<Pull>,
}
#[derive(Debug, Default)]
struct Pull {
red: u32,
green: u32,
blue: u32,
}
impl Games {
fn parser(input: &str) -> IResult<&str, Self> {
map(separated_list1(line_ending, Game::parser), Games)(input)
}
fn valid_game_id_sum(&self, max_pull: &Pull) -> u32 {
self.0
.iter()
.filter(|game| game.is_valid(max_pull))
.map(|game| game.id)
.sum()
}
fn power_sum(&self) -> u32 {
self.0.iter().map(|game| game.min_pull().power()).sum()
}
}
impl Game {
fn parser(input: &str) -> IResult<&str, Self> {
map(
tuple((
tag("Game "),
nom_u32,
tag(": "),
separated_list1(tag("; "), Pull::parser),
)),
|(_, id, _, pulls)| Game { id, pulls },
)(input)
}
fn is_valid(&self, max_pull: &Pull) -> bool {
self.pulls.iter().all(|pull| {
pull.red <= max_pull.red && pull.blue <= max_pull.blue && pull.green <= max_pull.green
})
}
fn min_pull(&self) -> Pull {
Pull {
red: self.pulls.iter().map(|p| p.red).max().unwrap_or(0),
blue: self.pulls.iter().map(|p| p.blue).max().unwrap_or(0),
green: self.pulls.iter().map(|p| p.green).max().unwrap_or(0),
}
}
}
impl Pull {
fn parser(input: &str) -> IResult<&str, Self> {
map(
separated_list1(tag(", "), tuple((nom_u32, tag(" "), alpha1))),
|stones| {
let mut pull = Pull::default();
for (quantity, _, colour) in stones {
match colour {
"red" => pull.red += quantity,
"blue" => pull.blue += quantity,
"green" => pull.green += quantity,
other => panic!("Unexpected colour, {}", other),
};
}
pull
},
)(input)
}
fn power(&self) -> u32 {
self.red * self.blue * self.green
}
}
|