Skip to content

Commit

Permalink
feat(2023-09): solve part 1 and 2
Browse files Browse the repository at this point in the history
  • Loading branch information
cor committed Dec 10, 2023
1 parent 3a1b304 commit ab3fa8b
Show file tree
Hide file tree
Showing 6 changed files with 276 additions and 0 deletions.
9 changes: 9 additions & 0 deletions 2023/09/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "aoc-2023-09"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aoc-2023-common = { path = "../common/" }
200 changes: 200 additions & 0 deletions 2023/09/input/1.txt

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions 2023/09/input/example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
56 changes: 56 additions & 0 deletions 2023/09/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use aoc_2023_common::challenge_input;

fn deltas(sequence: &[i64]) -> Vec<i64> {
sequence
.windows(2)
.filter_map(|window| match window {
[left, right] => Some(right - left),
_ => None,
})
.collect()
}

fn recursive_deltas(sequence: &[i64]) -> Vec<Vec<i64>> {
let mut sequences = vec![sequence.to_vec().clone()];
while !sequences.last().unwrap().iter().all(|&n| n == 0) {
let next = deltas(sequences.last().unwrap());
sequences.push(next);
}
sequences.pop(); // we don't care about [0, 0, ..]
sequences
}

fn extrapolate(sequence: &[i64]) -> i64 {
let mut deltas = recursive_deltas(sequence);

let len = deltas.len();
let smallest_delta = deltas[len - 1][0];
deltas[len - 1].push(smallest_delta);

for i in (0..len - 1).rev() {
let next = deltas[i].last().unwrap() + deltas[i + 1].last().unwrap();
deltas[i].push(next);
}

*deltas[0].last().unwrap()
}

fn main() {
let input = challenge_input();
let mut sequences: Vec<Vec<i64>> = input
.lines()
.map(|line| {
line.split_whitespace()
.filter_map(|num| num.parse().ok())
.collect()
})
.collect();

let part_1: i64 = sequences.iter().map(|seq| extrapolate(seq)).sum();
println!("{}", part_1);

sequences.iter_mut().for_each(|seq| seq.reverse());
let part_2: i64 = sequences.iter().map(|seq| extrapolate(seq)).sum();

println!("{}", part_2);
}
7 changes: 7 additions & 0 deletions 2023/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions 2023/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ members = [
"06",
"07",
"08",
"09",
]

0 comments on commit ab3fa8b

Please sign in to comment.