-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.rs
136 lines (112 loc) · 3.61 KB
/
day2.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
134
135
136
//! [Day 2: Cube Conundrum](https://adventofcode.com/2023/day/2)
struct Puzzle {
data: String, // raw puzzle input, it is parsed when needed
}
impl Puzzle {
fn new() -> Puzzle {
Puzzle {
data: String::new(),
}
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.data = data;
}
/// Solve part one.
fn part1(&self) -> u32 {
let mut sum = 0;
for line in self.data.lines() {
let s: Vec<_> = line.split(':').collect();
let valid = || {
let subsets = s.last().unwrap();
for subset in subsets.split(';') {
for cube in subset.split(',') {
let cube: Vec<_> = cube.trim().split(' ').collect();
let n = cube.first().unwrap().parse::<u32>().unwrap();
let color = cube.last();
let max_value = match color {
Some(&"red") => 12,
Some(&"green") => 13,
Some(&"blue") => 14,
_ => panic!(),
};
if n > max_value {
return false;
}
}
}
true
};
if valid() {
// get the id from "Game <id>"
let id = s
.first()
.unwrap()
.strip_prefix("Game ")
.unwrap()
.parse::<u32>()
.unwrap();
sum += id;
}
}
sum
}
/// Solve part two.
fn part2(&self) -> u32 {
let mut sum = 0;
for line in self.data.lines() {
let mut red = 0;
let mut green = 0;
let mut blue = 0;
// get the string at the right of ':'
let subsets = line.split(':').last().unwrap();
// split the sets of cubes
for subset in subsets.split(';') {
// split the cubes
for cube in subset.split(',') {
// cube is "<n> <color>"
let cube: Vec<_> = cube.trim().split(' ').collect();
let n = cube.first().unwrap().parse::<u32>().unwrap();
let color = cube.last();
// adjust max count of each colors
match color {
Some(&"red") => red = red.max(n),
Some(&"green") => green = green.max(n),
Some(&"blue") => blue = blue.max(n),
_ => panic!(),
};
}
}
// compute the power of the set of cubes
let power = red * green * blue;
// sum of the power of 'these) sets
sum += power;
}
sum
}
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 8);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 2286);
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}