Skip to content

Instantly share code, notes, and snippets.

@icub3d
Created December 9, 2023 17:49
Show Gist options
  • Save icub3d/02999552ae9612f8a599e43fb5b7ca82 to your computer and use it in GitHub Desktop.
Save icub3d/02999552ae9612f8a599e43fb5b7ca82 to your computer and use it in GitHub Desktop.
Advent of Code 2023 - Day 09
use std::collections::VecDeque;
fn find_next(history: &[isize], lasts: &mut VecDeque<isize>) -> isize {
let diffs = history.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
if diffs.iter().sum::<isize>() == 0 {
return lasts.iter().sum::<isize>();
}
lasts.push_back(diffs[diffs.len() - 1]);
find_next(&diffs, lasts)
}
fn find_prev(history: &[isize], firsts: &mut VecDeque<isize>) -> isize {
let diffs = history.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
if diffs.iter().sum::<isize>() == 0 {
return firsts.iter().rev().fold(0, |acc, x| x - acc);
}
firsts.push_back(diffs[0]);
find_prev(&diffs, firsts)
}
fn main() {
let input = std::fs::read_to_string("input").unwrap();
let histories = input
.lines()
.map(|l| {
l.split(' ')
.map(|d| d.parse::<isize>().unwrap())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let p1 = histories
.iter()
.map(|h| find_next(h, &mut VecDeque::from(vec![h[h.len() - 1]])))
.sum::<isize>();
println!("p1: {}", p1);
let p2 = histories
.iter()
.map(|h| find_prev(h, &mut VecDeque::from(vec![h[0]])))
.sum::<isize>();
println!("p2: {}", p2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment