1
0
Fork 0

day(09): factor out the ‹find_next›

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-09 13:17:30 +01:00
parent ab9a4bde33
commit 018ee668d4
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -6,6 +6,23 @@ type Output2 = Output1;
struct Day09 {
values: Vec<Vec<i32>>,
}
impl Day09 {
fn find_next(xs: &[i32]) -> i32 {
let mut ds = vec![];
let mut last_row = xs.to_owned();
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>()
}
}
impl Solution<Output1, Output2> for Day09 {
fn new<P: AsRef<Path>>(pathname: P) -> Self {
let values = file_to_lines::<Vec<_>, P>(pathname)
@ -17,42 +34,19 @@ impl Solution<Output1, Output2> for Day09 {
}
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()
self.values.iter().map(|xs| Self::find_next(xs)).sum()
}
fn part_2(&mut self) -> Output2 {
self.values
.iter()
.map(|xs| {
let mut ds = vec![];
let mut ys = xs.clone();
ys.reverse();
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>()
ys
})
.map(|xs| Self::find_next(&xs))
.sum()
}
}