1
0
Fork 0

day(09): add solution

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-09 13:11:33 +01:00
parent caa38e535a
commit ab9a4bde33
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 67 additions and 0 deletions

3
samples/day09.txt Normal file
View file

@ -0,0 +1,3 @@
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45

64
src/bin/day09.rs Normal file
View file

@ -0,0 +1,64 @@
use aoc_2023::*;
type Output1 = i32;
type Output2 = Output1;
struct Day09 {
values: Vec<Vec<i32>>,
}
impl Solution<Output1, Output2> for Day09 {
fn new<P: AsRef<Path>>(pathname: P) -> Self {
let values = file_to_lines::<Vec<_>, P>(pathname)
.iter()
.map(|vals| parse_ws_separated(vals))
.collect_vec();
Self { values }
}
fn part_1(&mut self) -> Output1 {
self.values
.iter()
.map(|xs| {
let mut ds = vec![];
let mut last_row = xs.clone();
while last_row.iter().any(|&x| x != 0) {
let next_row = last_row.windows(2).map(|s| s[1] - s[0]).collect_vec();
ds.push(*next_row.last().unwrap());
last_row = next_row;
}
xs.last().unwrap() + ds.iter().rev().sum::<i32>()
})
.sum()
}
fn part_2(&mut self) -> Output2 {
self.values
.iter()
.map(|xs| {
let mut ds = vec![];
let mut last_row = xs.clone();
last_row.reverse();
while last_row.iter().any(|&x| x != 0) {
let next_row = last_row.windows(2).map(|s| s[1] - s[0]).collect_vec();
ds.push(*next_row.last().unwrap());
last_row = next_row;
}
xs.first().unwrap() + ds.iter().rev().sum::<i32>()
})
.sum()
}
}
fn main() -> Result<()> {
Day09::main()
}
test_sample!(day_09, Day09, 114, 2);