day 9 part 2

This commit is contained in:
Dominic 2023-12-09 12:47:59 +01:00
parent 2fcf53d561
commit fe9cf52452
Signed by: msrd0
GPG key ID: DCC8C247452E98F9

View file

@ -2,7 +2,7 @@
#![forbid(elided_lifetimes_in_paths, unsafe_code)]
use aoc23::read;
use chumsky::{prelude::*, text::int};
use chumsky::prelude::*;
struct History(Vec<i64>);
@ -31,8 +31,7 @@ fn parser() -> impl Parser<char, Vec<History>, Error = Simple<char>> {
impl History {
fn diff(&self) -> Self {
// intentionally reserve one space extra for .extend()
let mut diffs = Vec::with_capacity(self.0.len());
let mut diffs = Vec::with_capacity(self.0.len() - 1);
if self.0.len() > 1 {
for i in 1 .. self.0.len() {
diffs.push(self.0[i] - self.0[i - 1]);
@ -41,13 +40,23 @@ impl History {
Self(diffs)
}
fn extend(&mut self) {
fn extend_last(&self) -> i64 {
if self.0.iter().any(|num| *num != 0) {
let mut diff = self.diff();
diff.extend();
self.0.push(self.0.last().unwrap() + diff.0.last().unwrap());
let diff = self.diff();
let last = diff.extend_last();
self.0.last().unwrap() + last
} else {
self.0.push(0);
0
}
}
fn extend_first(&self) -> i64 {
if self.0.iter().any(|num| *num != 0) {
let diff = self.diff();
let first = diff.extend_first();
self.0.first().unwrap() - first
} else {
0
}
}
}
@ -55,12 +64,14 @@ impl History {
fn main() -> anyhow::Result<()> {
let histories = read("inputs/day9.txt", parser())?;
let mut sum = 0;
for mut h in histories {
h.extend();
sum += h.0.last().unwrap();
let mut sum_last = 0;
let mut sum_first = 0;
for h in histories {
sum_last += h.extend_last();
sum_first += h.extend_first();
}
println!("{sum}");
println!("{sum_last}");
println!("{sum_first}");
Ok(())
}