day(09): do ‹find_next› in-situ
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
018ee668d4
commit
4a2e0fef55
1 changed files with 12 additions and 10 deletions
|
@ -8,18 +8,20 @@ struct Day09 {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Day09 {
|
impl Day09 {
|
||||||
fn find_next(xs: &[i32]) -> i32 {
|
fn find_next(mut xs: Vec<i32>) -> i32 {
|
||||||
|
let last = *xs.last().unwrap();
|
||||||
|
|
||||||
let mut ds = vec![];
|
let mut ds = vec![];
|
||||||
|
while xs.iter().any(|&x| x != 0) {
|
||||||
|
for i in 0..xs.len() - 1 {
|
||||||
|
xs[i] = xs[i + 1] - xs[i];
|
||||||
|
}
|
||||||
|
xs.pop();
|
||||||
|
|
||||||
let mut last_row = xs.to_owned();
|
ds.push(*xs.last().unwrap());
|
||||||
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>()
|
last + ds.iter().rev().sum::<i32>()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -34,7 +36,7 @@ impl Solution<Output1, Output2> for Day09 {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn part_1(&mut self) -> Output1 {
|
fn part_1(&mut self) -> Output1 {
|
||||||
self.values.iter().map(|xs| Self::find_next(xs)).sum()
|
self.values.iter().cloned().map(Self::find_next).sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn part_2(&mut self) -> Output2 {
|
fn part_2(&mut self) -> Output2 {
|
||||||
|
@ -46,7 +48,7 @@ impl Solution<Output1, Output2> for Day09 {
|
||||||
|
|
||||||
ys
|
ys
|
||||||
})
|
})
|
||||||
.map(|xs| Self::find_next(&xs))
|
.map(Self::find_next)
|
||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue