Rust: do a day 9

This commit is contained in:
Sijmen 2020-12-15 22:28:25 +01:00
parent e03fc564c1
commit e13d0225bc
Signed by: vijfhoek
GPG Key ID: DAF7821E067D9C48
1 changed files with 56 additions and 5 deletions

View File

@ -378,10 +378,61 @@ mod day08 {
} }
mod day09 { mod day09 {
use std::time::Duration; use std::time::{Duration, Instant};
pub fn run(_: bool) -> Duration { fn part1(numbers: &[usize]) -> usize {
Duration::new(0, 0) 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<usize> = 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() { for day in 0..days.len() {
let first_run = days[day](false); let first_run = days[day](false);
if first_run.as_nanos() == 0 { if first_run.as_nanos() == 0 {
println!("Day {:>2}: skipped", day); println!("Day {:>2}: skipped", day + 1);
continue; continue;
} }
@ -510,7 +561,7 @@ fn main() {
total += elapsed; total += elapsed;
} }
println!("-------------------"); println!("--------------------");
println!("Total: {:?}", total); println!("Total: {:?}", total);
} }
} }