70 lines
1.7 KiB
Rust
70 lines
1.7 KiB
Rust
use crate::day_solver::DaySolver;
|
|
#[cfg(test)]
|
|
use crate::util::read_file;
|
|
|
|
pub struct Day9 {
|
|
histories: Vec<Vec<i32>>
|
|
}
|
|
|
|
impl Day9 {
|
|
|
|
pub fn create(input: String) -> Self {
|
|
return Day9 {
|
|
histories: input.lines().map(|h| h.split_whitespace().map(|n| n.parse().unwrap()).collect()).collect()
|
|
}
|
|
}
|
|
}
|
|
|
|
fn find_next_in_history(history: &Vec<i32>) -> i32 {
|
|
|
|
if history.iter().all(|n| n == &0) {
|
|
return 0
|
|
}
|
|
|
|
let mut history_derivative = Vec::with_capacity(history.len());
|
|
for i in 0..history.len() - 1 {
|
|
history_derivative.push(history[i + 1] - history[i])
|
|
}
|
|
|
|
return history.last().unwrap() + find_next_in_history(&history_derivative);
|
|
|
|
}
|
|
|
|
impl DaySolver for Day9 {
|
|
|
|
|
|
fn solve_part1(&mut self) -> String {
|
|
return self.histories.iter()
|
|
.map(|h| {
|
|
let res = find_next_in_history(h);
|
|
// println!("{:?} yields {}", h, res);
|
|
res
|
|
})
|
|
.sum::<i32>().to_string()
|
|
}
|
|
|
|
fn solve_part2(&mut self) -> String {
|
|
return self.histories.iter()
|
|
.map(|h| {
|
|
let mut h_reverse = h.clone();
|
|
h_reverse.reverse();
|
|
let res = find_next_in_history(&h_reverse);
|
|
// println!("{:?} yields {}", h, res);
|
|
res
|
|
})
|
|
.sum::<i32>().to_string()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_part1() {
|
|
let mut day = Day9::create(read_file("input/day09_example.txt"));
|
|
assert_eq!("114", day.solve_part1());
|
|
}
|
|
|
|
#[test]
|
|
fn test_part2() {
|
|
let mut day = Day9::create(read_file("input/day09_example.txt"));
|
|
assert_eq!("2", day.solve_part2());
|
|
}
|