day(09): factor out the ‹find_next›
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
ab9a4bde33
commit
018ee668d4
1 changed files with 22 additions and 28 deletions
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue