2023: Day 9, part 2

This commit is contained in:
Wesley Moore 2023-12-09 16:05:00 +10:00
parent 59feeb7fec
commit 7f166a5075
No known key found for this signature in database

View file

@ -11,15 +11,19 @@ fn main() -> Result<(), BoxError> {
.next()
.ok_or("missing input file path")?;
let file = BufReader::new(File::open(input_path)?);
let mut sum = 0;
let mut part1 = 0;
let mut part2 = 0;
for line in file.lines() {
let line = line?;
let history = parse_line(&line)?;
let value = calculate_next_value(&history);
sum += value;
let prev_value = calculate_prev_value(&history);
part1 += value;
part2 += prev_value;
}
println!("Part 1: {sum}");
println!("Part 1: {part1}");
println!("Part 2: {part2}");
Ok(())
}
@ -31,15 +35,7 @@ fn parse_line(line: &str) -> Result<Vec<i32>, ParseIntError> {
}
fn calculate_next_value(history: &[i32]) -> i32 {
let x: Vec<_> = history
.windows(2)
.map(|window| {
let &[a, b] = window else {
unreachable!("window is not a pair")
};
b - a
})
.collect();
let x = window_differences(history);
// See if they're all the same, if so then the next value is the same
let first = x[0];
@ -50,3 +46,29 @@ fn calculate_next_value(history: &[i32]) -> i32 {
calculate_next_value(&x)
}
}
fn calculate_prev_value(history: &[i32]) -> i32 {
let x = window_differences(history);
// See if they're all the same, if so then the next value is the same
let same = x[0];
let first = history.first().unwrap();
first
- if x.iter().all(|val| *val == same) {
same
} else {
calculate_prev_value(&x)
}
}
fn window_differences(values: &[i32]) -> Vec<i32> {
values
.windows(2)
.map(|window| {
let &[a, b] = window else {
unreachable!("window is not a pair")
};
b - a
})
.collect()
}