Day9 Rust
This commit is contained in:
37
day9/rust/src/main.rs
Normal file
37
day9/rust/src/main.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user