Added day 9-1
This commit is contained in:
37
src/days/day9.rs
Normal file
37
src/days/day9.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use std::{path::Path, str::FromStr};
|
||||
|
||||
use crate::{error::AdventError, input::read_into_vec};
|
||||
|
||||
struct Series(Vec<i32>);
|
||||
|
||||
impl FromStr for Series {
|
||||
type Err = AdventError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Series(s.trim().split_whitespace().map(|x| {
|
||||
Ok(i32::from_str(x)?)
|
||||
}).collect::<Result<Vec<i32>, AdventError>>()?))
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
})? as u64)
|
||||
}
|
||||
|
||||
fn predict_next(series: &[i32]) -> 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)?)
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn two() -> Result<u64, AdventError> {
|
||||
Ok(0)
|
||||
}
|
||||
@@ -5,4 +5,5 @@ pub mod day4;
|
||||
pub mod day5;
|
||||
pub mod day6;
|
||||
pub mod day7;
|
||||
pub mod day8;
|
||||
pub mod day8;
|
||||
pub mod day9;
|
||||
@@ -19,6 +19,7 @@ fn main() -> Result<(), AdventError> {
|
||||
(day6::one as fn() -> Result<u64, AdventError>, day6::two as fn() -> Result<u64, AdventError>),
|
||||
(day7::one as fn() -> Result<u64, AdventError>, day7::two as fn() -> Result<u64, AdventError>),
|
||||
(day8::one as fn() -> Result<u64, AdventError>, day8::two as fn() -> Result<u64, AdventError>),
|
||||
(day9::one as fn() -> Result<u64, AdventError>, day9::two as fn() -> Result<u64, AdventError>),
|
||||
];
|
||||
|
||||
if env::args().len() == 1 {
|
||||
|
||||
Reference in New Issue
Block a user