day9: optimized

This commit is contained in:
Ishan Jain 2023-12-09 12:05:04 +05:30
parent 23967c2689
commit 4a69aeffe5
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27
2 changed files with 20 additions and 24 deletions

View File

@ -11,31 +11,26 @@ fn process(data: &str) -> i64 {
if line.is_empty() {
continue;
}
let mut input: Vec<i64> = line
.split(' ')
.filter(|x| !x.is_empty())
.map(|x| x.parse::<i64>().unwrap())
.collect();
let input: Vec<i64> = line.split(' ').flat_map(|x| x.parse::<i64>()).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<i64> = last.windows(2).map(|win| win[1] - win[0]).collect();
while input.iter().any(|&x| x != 0) {
let diff: Vec<i64> = 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

View File

@ -12,25 +12,26 @@ fn process(data: &str) -> i64 {
if line.is_empty() {
continue;
}
let mut input: Vec<i64> = line.split(' ').map(|x| x.parse::<i64>().unwrap()).collect();
let input: Vec<i64> = line.split(' ').flat_map(|x| x.parse::<i64>()).collect();
let mut diffs = vec![input.clone()];
let mut diffs = vec![input];
while input.iter().any(|&x| x != 0) {
let diff: Vec<i64> = 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<i64> = 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