Skip to content

Instantly share code, notes, and snippets.

@typester
Created December 12, 2023 05:11
Show Gist options
  • Save typester/2243a37571a0e7ab2aeeb8486290eb17 to your computer and use it in GitHub Desktop.
Save typester/2243a37571a0e7ab2aeeb8486290eb17 to your computer and use it in GitHub Desktop.
2023 Advent of Code Day 9
const INPUT: &str = "..snip..";
fn main() {
let sum: i64 = INPUT.lines()
.map(extract_digits)
.map(|d| extrapolate_next(&d))
.sum();
println!("part1: {}", sum);
let sum: i64 = INPUT.lines()
.map(extract_digits)
.map(|d| extrapolate_prev(&d))
.sum();
println!("part2: {}", sum);
}
fn extract_digits(line: &str) -> Vec<i64> {
let mut r: Vec<i64> = vec![];
let mut buf = String::new();
for c in line.chars() {
if c == ' ' && buf.len() > 0 {
r.push(buf.parse().unwrap());
buf.clear();
} else if c.is_numeric() || c == '-' {
buf.push(c);
}
}
if buf.len() > 0 {
r.push(buf.parse().unwrap());
}
r
}
fn extrapolate_next(n: &Vec<i64>) -> i64 {
let mut seqs: Vec<Vec<i64>> = vec![];
seqs.push(n.clone());
while seqs[ seqs.len() - 1 ].iter().all(|&v| v == 0) == false {
let next = seqs[ seqs.len() - 1]
.windows(2)
.map(|w| w[1] - w[0])
.collect();
seqs.push(next);
}
let mut i = seqs.len();
while i >= 2 {
let l = seqs[i - 1][ seqs[i-1].len() - 1 ];
let l2 = seqs.get_mut(i - 2).unwrap();
l2.push(
l2[l2.len() - 1] + l
);
i -= 1;
}
seqs[0][ seqs[0].len() - 1 ]
}
fn extrapolate_prev(n: &Vec<i64>) -> i64 {
let mut seqs: Vec<Vec<i64>> = vec![];
seqs.push(n.clone());
while seqs[ seqs.len() - 1 ].iter().all(|&v| v == 0) == false {
let next = seqs[ seqs.len() - 1]
.windows(2)
.map(|w| w[1] - w[0])
.collect();
seqs.push(next);
}
let mut i = seqs.len();
while i >= 2 {
let l = seqs[i - 1][0];
let l2 = seqs.get_mut(i - 2).unwrap();
l2.insert(0, l2[0] - l);
i -= 1;
}
seqs[0][0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment