-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday3.rs
More file actions
169 lines (142 loc) · 4.16 KB
/
day3.rs
File metadata and controls
169 lines (142 loc) · 4.16 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use std::{fs, str::FromStr};
struct Problem {
battery_banks: Vec<BatteryBank>,
}
impl Problem {
pub fn part_1(&self) -> u64 {
self.battery_banks
.iter()
.map(|bank| bank.largest_joltage_n(2))
.sum()
}
pub fn part_2(&self) -> u64 {
self.battery_banks
.iter()
.map(|bank| bank.largest_joltage_n(12))
.sum()
}
}
impl FromStr for Problem {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
battery_banks: s
.trim()
.lines()
.map(|line| line.parse::<BatteryBank>())
.collect::<Result<Vec<BatteryBank>, _>>()?,
})
}
}
struct BatteryBank {
batteries: Vec<Battery>,
}
impl FromStr for BatteryBank {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
batteries: s
.trim()
.chars()
.map(|char| char.to_string().parse::<Battery>())
.collect::<Result<Vec<Battery>, _>>()?,
})
}
}
impl BatteryBank {
fn max_rating_index(&self) -> usize {
self.batteries
.iter()
.map(|battery| battery.rating)
.enumerate()
.reduce(|el_max, el_current| {
if el_current.1 > el_max.1 {
el_current
} else {
el_max
}
})
.unwrap()
.0
}
fn largest_joltage_n(&self, n: usize) -> u64 {
let mut pick_offset = 0;
let mut pick_ratings: Vec<u32> = Vec::with_capacity(n);
// Pick exactly n battery ratings from the bank
for i in 0..n {
// We need to pick n-i subsequent ratings, so check all up to the (n-i)th (inclusive)
let n_to_pick = n - i;
// println!(
// "Picking from range [{}..={}]",
// pick_offset,
// self.batteries.len() - n_to_pick
// );
let bank = Self {
batteries: self.batteries[pick_offset..=self.batteries.len() - n_to_pick].to_vec(),
};
// Determine the index of the battery with the max joltage rating
let i_bank_max = bank.max_rating_index();
// Add the corresponding joltage rating to the ratings picked so far
pick_ratings.push(bank.batteries[i_bank_max].rating);
// Update offset so that subsequent batteries are picked after the last chosen one
pick_offset += i_bank_max + 1;
// println!(
// "{}: max {} at position {}",
// i,
// bank.batteries[i_bank_max].rating,
// pick_offset - 1,
// );
}
// Construct the joltage from the picked joltage ratings
pick_ratings
.iter()
.map(|rating| rating.to_string())
.collect::<String>()
.parse()
.unwrap()
}
}
#[derive(Clone)]
struct Battery {
rating: u32,
}
impl FromStr for Battery {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
rating: s
.trim()
.chars()
.nth(0)
.ok_or("No joltage value found")?
.to_digit(10)
.ok_or("Invalid joltage value given")?,
})
}
}
fn main() {
let problem = fs::read_to_string("input/day3.txt")
.expect("Failed to read input")
.parse::<Problem>()
.unwrap();
println!("Part 1: {}", problem.part_1()); // Attempts: 17330, 17493
println!("Part 2: {}", problem.part_2()); // Attempts: 173685428989126
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &str = r#"
987654321111111
811111111111119
234234234234278
818181911112111
"#;
#[test]
fn test_sample_part_1() {
assert_eq!(357, SAMPLE.parse::<Problem>().unwrap().part_1());
}
#[test]
fn test_sample_part_2() {
assert_eq!(3121910778619, SAMPLE.parse::<Problem>().unwrap().part_2());
}
}