44 lines
1.5 KiB
Rust
44 lines
1.5 KiB
Rust
use std::fs::read_to_string;
|
|
|
|
fn get_numbers_in_line_iter<T: std::str::FromStr>(str: &str) -> impl Iterator<Item=T> + '_ {
|
|
str.split_whitespace().filter_map(|substr| substr.parse::<T>().ok())
|
|
}
|
|
|
|
fn main() {
|
|
let mut sum1 = 0;
|
|
let mut sum2 = 0;
|
|
let mut working_vec: Vec<i32> = Vec::new();
|
|
for line in read_to_string("input.txt").unwrap().lines() {
|
|
working_vec.extend(get_numbers_in_line_iter::<i32>(line));
|
|
let mut extrapolated1 = 0;
|
|
let mut extrapolated2 = 0;
|
|
let mut sequence_length = working_vec.len() - 1;
|
|
while sequence_length > 0 {
|
|
let mut all_zeros = true;
|
|
// accumulate last element for task 1
|
|
extrapolated1 += working_vec[sequence_length];
|
|
// accumulate first element with subtraction for task 2
|
|
extrapolated2 = working_vec[0] - extrapolated2;
|
|
for i in 0..sequence_length {
|
|
working_vec[i] = working_vec[i + 1] - working_vec[i];
|
|
if working_vec[i] != 0 {
|
|
all_zeros = false;
|
|
}
|
|
}
|
|
if all_zeros {
|
|
break;
|
|
}
|
|
sequence_length -= 1;
|
|
}
|
|
// flip sign if there was an even amount of elements to account for processing it in reverse
|
|
if (working_vec.len() - sequence_length) % 2 == 0 {
|
|
extrapolated2 = -extrapolated2;
|
|
}
|
|
sum1 += extrapolated1;
|
|
sum2 += extrapolated2;
|
|
working_vec.clear();
|
|
}
|
|
println!("Sum1: {}", sum1);
|
|
println!("Sum2: {}", sum2);
|
|
}
|