From 6f097df1cdca80b6754706986f7609c765637b3a Mon Sep 17 00:00:00 2001 From: Dennis Brentjes Date: Mon, 11 Dec 2023 19:45:41 +0100 Subject: [PATCH] Added day 9-2 --- src/days/day9.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/days/day9.rs b/src/days/day9.rs index cc6f6f4..7e067e6 100644 --- a/src/days/day9.rs +++ b/src/days/day9.rs @@ -17,21 +17,28 @@ impl FromStr for Series { pub fn one() -> Result { let series = read_into_vec::(Path::new("resources/input9.txt"))?; Ok(series.iter().fold(Ok(0i64), | acc: Result, Series(series) | { - Ok(acc? + (predict_next(series)? as i64)) + Ok(acc? + (predict_next(series, true)? as i64)) })? as u64) } -fn predict_next(series: &[i32]) -> Result { +fn predict_next(series: &[i32], next: bool) -> Result { if !series.iter().all(|x| *x == 0) { let diff_vec: Vec = series.iter().zip(series.iter().skip(1)).map(|(lh, rh)| { *rh - *lh }).collect::>(); - Ok(series.last().ok_or(AdventError("No last element in array?".into()))? + predict_next(&diff_vec)?) + if next { + Ok(series.last().ok_or(AdventError("No last element in array?".into()))? + predict_next(&diff_vec, next)?) + } else { + Ok(series.first().ok_or(AdventError("No first element in array?".into()))? - predict_next(&diff_vec, next)?) + } } else { Ok(0) } } pub fn two() -> Result { - Ok(0) + let series = read_into_vec::(Path::new("resources/input9.txt"))?; + Ok(series.iter().fold(Ok(0i64), | acc: Result, Series(series) | { + Ok(acc? + (predict_next(series, false)? as i64)) + })? as u64) } \ No newline at end of file