Rust: do a day 9
This commit is contained in:
parent
e03fc564c1
commit
e13d0225bc
1 changed files with 56 additions and 5 deletions
|
@ -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<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() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue