[TASK] Solved day 9
This commit is contained in:
69
src/day9.rs
Normal file
69
src/day9.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
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());
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::day5::Day5;
|
||||
use crate::day6::Day6;
|
||||
use crate::day7::Day7;
|
||||
use crate::day8::Day8;
|
||||
use crate::day9::Day9;
|
||||
use crate::day_solver::DaySolver;
|
||||
use crate::util::read_file;
|
||||
|
||||
@@ -22,8 +23,9 @@ mod day5;
|
||||
mod day6;
|
||||
mod day7;
|
||||
mod day8;
|
||||
mod day9;
|
||||
|
||||
const MAX_DAY: u8 = 8;
|
||||
const MAX_DAY: u8 = 9;
|
||||
const DEFAULT_BENCHMARK_AMOUNT: u32 = 100;
|
||||
|
||||
fn main() {
|
||||
@@ -102,6 +104,7 @@ fn build_day_solver(day: u8, input: String) -> Option<Box<dyn DaySolver>> {
|
||||
6 => Some(Box::new(Day6::create(input))),
|
||||
7 => Some(Box::new(Day7::create(input))),
|
||||
8 => Some(Box::new(Day8::create(input))),
|
||||
9 => Some(Box::new(Day9::create(input))),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user