mirror of
https://github.com/wezm/advent-of-code.git
synced 2025-01-03 01:49:55 +00:00
2023: Day 9, part 2
This commit is contained in:
parent
59feeb7fec
commit
7f166a5075
1 changed files with 34 additions and 12 deletions
|
@ -11,15 +11,19 @@ fn main() -> Result<(), BoxError> {
|
||||||
.next()
|
.next()
|
||||||
.ok_or("missing input file path")?;
|
.ok_or("missing input file path")?;
|
||||||
let file = BufReader::new(File::open(input_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() {
|
for line in file.lines() {
|
||||||
let line = line?;
|
let line = line?;
|
||||||
let history = parse_line(&line)?;
|
let history = parse_line(&line)?;
|
||||||
let value = calculate_next_value(&history);
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -31,15 +35,7 @@ fn parse_line(line: &str) -> Result<Vec<i32>, ParseIntError> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn calculate_next_value(history: &[i32]) -> i32 {
|
fn calculate_next_value(history: &[i32]) -> i32 {
|
||||||
let x: Vec<_> = history
|
let x = window_differences(history);
|
||||||
.windows(2)
|
|
||||||
.map(|window| {
|
|
||||||
let &[a, b] = window else {
|
|
||||||
unreachable!("window is not a pair")
|
|
||||||
};
|
|
||||||
b - a
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// See if they're all the same, if so then the next value is the same
|
// See if they're all the same, if so then the next value is the same
|
||||||
let first = x[0];
|
let first = x[0];
|
||||||
|
@ -50,3 +46,29 @@ fn calculate_next_value(history: &[i32]) -> i32 {
|
||||||
calculate_next_value(&x)
|
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()
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue