From 018ee668d40a4cb8ba8318c5c6f46f42c97c0cbf Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 9 Dec 2023 13:17:30 +0100 Subject: [PATCH] =?UTF-8?q?day(09):=20factor=20out=20the=20=E2=80=B9find?= =?UTF-8?q?=5Fnext=E2=80=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- src/bin/day09.rs | 50 +++++++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 28 deletions(-) diff --git a/src/bin/day09.rs b/src/bin/day09.rs index 89df934..81bb313 100644 --- a/src/bin/day09.rs +++ b/src/bin/day09.rs @@ -6,6 +6,23 @@ type Output2 = Output1; struct Day09 { values: Vec>, } + +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::() + } +} + impl Solution for Day09 { fn new>(pathname: P) -> Self { let values = file_to_lines::, P>(pathname) @@ -17,42 +34,19 @@ impl Solution 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::() - }) - .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::() + ys }) + .map(|xs| Self::find_next(&xs)) .sum() } }