Added day 9-2
This commit is contained in:
parent
9fabfcc9d9
commit
6f097df1cd
@ -17,21 +17,28 @@ impl FromStr for Series {
|
||||
pub fn one() -> Result<u64, AdventError> {
|
||||
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)? as i64))
|
||||
Ok(acc? + (predict_next(series, true)? as i64))
|
||||
})? 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) {
|
||||
let diff_vec: Vec<i32> = series.iter().zip(series.iter().skip(1)).map(|(lh, rh)| {
|
||||
*rh - *lh
|
||||
}).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 {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user