Files
adventofcode2023/day9/rust/src/main.rs
2023-12-09 22:19:40 +01:00

38 lines
884 B
Rust

enum Direction {
Forward,
Backward,
}
fn main() {
let stdin = std::io::stdin();
let mut part1 = 0;
let mut part2 = 0;
for line in stdin.lines() {
let line = line.unwrap();
let history = line.split(" ").map(|e| e.parse().unwrap()).collect();
part1 += extrapolate(&history, Direction::Forward);
part2 += extrapolate(&history, Direction::Backward);
}
println!("{}", part1);
println!("{}", part2);
}
fn extrapolate(history: &Vec<isize>, direction: Direction) -> isize {
if history.iter().all(|e| *e == 0) {
return 0;
}
let new_history = history.windows(2).map(|pair| pair[1] - pair[0]).collect();
if let Direction::Forward = direction {
return history.last().unwrap() + extrapolate(&new_history, direction);
}
return history[0] - extrapolate(&new_history, direction);
}