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