From 4a69aeffe5a8ef60a68591b29e21543eef8a36d1 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Sat, 9 Dec 2023 12:05:04 +0530 Subject: [PATCH] day9: optimized --- src/day9/1.rs | 25 ++++++++++--------------- src/day9/2.rs | 19 ++++++++++--------- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/src/day9/1.rs b/src/day9/1.rs index 807532f..16b589c 100644 --- a/src/day9/1.rs +++ b/src/day9/1.rs @@ -11,31 +11,26 @@ fn process(data: &str) -> i64 { if line.is_empty() { continue; } - let mut input: Vec = line - .split(' ') - .filter(|x| !x.is_empty()) - .map(|x| x.parse::().unwrap()) - .collect(); + let input: Vec = line.split(' ').flat_map(|x| x.parse::()).collect(); - let mut diffs = vec![input.clone()]; + let mut diffs = vec![input]; + + while let Some(last) = diffs.last() { + if !last.iter().any(|&x| x != 0) { + break; + } + let diff: Vec = last.windows(2).map(|win| win[1] - win[0]).collect(); - while input.iter().any(|&x| x != 0) { - let diff: Vec = input.windows(2).map(|win| win[1] - win[0]).collect(); - input = diff.clone(); diffs.push(diff); } let mut prev_inserted = 0; - - for diff in diffs.iter_mut().rev() { + for diff in diffs.drain(..).rev() { let last = diff[diff.len() - 1]; let num = prev_inserted + last; - diff.push(num); - prev_inserted = num; } - - answer += diffs[0].last().unwrap(); + answer += prev_inserted; } answer diff --git a/src/day9/2.rs b/src/day9/2.rs index ec5ccaa..be9f74c 100644 --- a/src/day9/2.rs +++ b/src/day9/2.rs @@ -12,25 +12,26 @@ fn process(data: &str) -> i64 { if line.is_empty() { continue; } - let mut input: Vec = line.split(' ').map(|x| x.parse::().unwrap()).collect(); + let input: Vec = line.split(' ').flat_map(|x| x.parse::()).collect(); - let mut diffs = vec![input.clone()]; + let mut diffs = vec![input]; - while input.iter().any(|&x| x != 0) { - let diff: Vec = input.windows(2).map(|win| win[1] - win[0]).collect(); - input = diff.clone(); + while let Some(last) = diffs.last() { + if !last.iter().any(|&x| x != 0) { + break; + } + let diff: Vec = last.windows(2).map(|win| win[1] - win[0]).collect(); diffs.push(diff); } let mut prev_inserted = 0; - for diff in diffs.iter_mut().rev() { + for diff in diffs.drain(..).rev() { let last = diff[0]; - let num = last - prev_inserted; - diff.insert(0, num); prev_inserted = num; } - answer += diffs[0].first().unwrap(); + + answer += prev_inserted; } answer