diff --git a/rust/src/main.rs b/rust/src/main.rs index 32aadf4..726019e 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -378,10 +378,61 @@ mod day08 { } mod day09 { - use std::time::Duration; + use std::time::{Duration, Instant}; - pub fn run(_: bool) -> Duration { - Duration::new(0, 0) + fn part1(numbers: &[usize]) -> usize { + for (i, &n) in numbers.iter().enumerate().skip(COUNT) { + let mut found = false; + for x in i - COUNT..i { + for y in x + 1..i { + if numbers[x] + numbers[y] == n { + found = true; + } + } + } + + if !found { + return n; + } + } + + panic!(); + } + + fn part2(numbers: &[usize], part1: usize) -> usize { + let mut lower = 0; + let mut upper = 0; + let mut sum = 0; + + while sum != part1 { + while sum < part1 { + sum += numbers[upper]; + upper += 1; + } + + while sum > part1 { + sum -= numbers[lower]; + lower += 1; + } + } + + numbers[lower..upper].iter().min().unwrap() + numbers[lower..upper].iter().max().unwrap() + } + + const COUNT: usize = 25; + pub fn run(print: bool) -> Duration { + let input = std::fs::read_to_string("../inputs/09").unwrap(); + let instant = Instant::now(); + + let numbers: Vec = input.split('\n').flat_map(str::parse).collect(); + let part1 = part1(&numbers); + let part2 = part2(&numbers, part1); + + if print { + dbg!(part1, part2); + } + + instant.elapsed() } } @@ -495,7 +546,7 @@ fn main() { for day in 0..days.len() { let first_run = days[day](false); if first_run.as_nanos() == 0 { - println!("Day {:>2}: skipped", day); + println!("Day {:>2}: skipped", day + 1); continue; } @@ -510,7 +561,7 @@ fn main() { total += elapsed; } - println!("-------------------"); + println!("--------------------"); println!("Total: {:?}", total); } }