Minor simplifications (less vector pushing)

This commit is contained in:
Acvaxoort 2023-12-10 16:43:12 +01:00
parent 259abbdddb
commit 29812f29f6

View File

@ -10,11 +10,15 @@ fn main() {
let mut working_vec: Vec<i32> = Vec::new(); let mut working_vec: Vec<i32> = Vec::new();
for line in read_to_string("input.txt").unwrap().lines() { for line in read_to_string("input.txt").unwrap().lines() {
working_vec.extend(get_numbers_in_line_iter::<i32>(line)); working_vec.extend(get_numbers_in_line_iter::<i32>(line));
let original_length = working_vec.len(); let mut extrapolated1 = 0;
let mut extrapolated2 = 0;
let mut sequence_length = working_vec.len() - 1; let mut sequence_length = working_vec.len() - 1;
while sequence_length > 0 { while sequence_length > 0 {
let mut all_zeros = true; let mut all_zeros = true;
working_vec.push(working_vec[0]); // 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 { for i in 0..sequence_length {
working_vec[i] = working_vec[i + 1] - working_vec[i]; working_vec[i] = working_vec[i + 1] - working_vec[i];
if working_vec[i] != 0 { if working_vec[i] != 0 {
@ -26,9 +30,10 @@ fn main() {
} }
sequence_length -= 1; sequence_length -= 1;
} }
let extrapolated1 = working_vec[sequence_length..original_length].iter().sum::<i32>(); // flip sign if there was an even amount of elements to account for processing it in reverse
let extrapolated2 = working_vec[original_length..].iter().rev().fold( if (working_vec.len() - sequence_length) % 2 == 0 {
0, |acc, x| x - acc); extrapolated2 = -extrapolated2;
}
sum1 += extrapolated1; sum1 += extrapolated1;
sum2 += extrapolated2; sum2 += extrapolated2;
working_vec.clear(); working_vec.clear();