Added day 9-2

This commit is contained in:
Dennis Brentjes 2023-12-11 19:45:41 +01:00
parent 9fabfcc9d9
commit 6f097df1cd

View File

@ -17,21 +17,28 @@ impl FromStr for Series {
pub fn one() -> Result<u64, AdventError> { pub fn one() -> Result<u64, AdventError> {
let series = read_into_vec::<Series>(Path::new("resources/input9.txt"))?; let series = read_into_vec::<Series>(Path::new("resources/input9.txt"))?;
Ok(series.iter().fold(Ok(0i64), | acc: Result<i64, AdventError>, Series(series) | { Ok(series.iter().fold(Ok(0i64), | acc: Result<i64, AdventError>, Series(series) | {
Ok(acc? + (predict_next(series)? as i64)) Ok(acc? + (predict_next(series, true)? as i64))
})? as u64) })? as u64)
} }
fn predict_next(series: &[i32]) -> Result<i32, AdventError> { fn predict_next(series: &[i32], next: bool) -> Result<i32, AdventError> {
if !series.iter().all(|x| *x == 0) { if !series.iter().all(|x| *x == 0) {
let diff_vec: Vec<i32> = series.iter().zip(series.iter().skip(1)).map(|(lh, rh)| { let diff_vec: Vec<i32> = series.iter().zip(series.iter().skip(1)).map(|(lh, rh)| {
*rh - *lh *rh - *lh
}).collect::<Vec<i32>>(); }).collect::<Vec<i32>>();
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 { } else {
Ok(0) Ok(0)
} }
} }
pub fn two() -> Result<u64, AdventError> { pub fn two() -> Result<u64, AdventError> {
Ok(0) let series = read_into_vec::<Series>(Path::new("resources/input9.txt"))?;
Ok(series.iter().fold(Ok(0i64), | acc: Result<i64, AdventError>, Series(series) | {
Ok(acc? + (predict_next(series, false)? as i64))
})? as u64)
} }