add timekeeping, also day1 that got left out somehow

This commit is contained in:
Joseph Montanaro 2021-12-03 11:28:22 -08:00
parent cf1fb4c792
commit 7681bbc760
2 changed files with 51 additions and 4 deletions

31
2021/src/day1.rs Normal file
View File

@ -0,0 +1,31 @@
use color_eyre::eyre;
use crate::lib::ParseLines;
fn run(data: &str) -> eyre::Result<()> {
let mut single_increases = 0;
let mut window_increases = 0;
let mut prev = (None, None, None);
for res in data.parse_lines::<i32>() {
let n = res?;
if let Some(p) = prev.2 {
// apparently we can't combine "if let" and regular boolean conditions
if n > p {
single_increases += 1;
}
}
if let (Some(first), Some(second), Some(third)) = prev {
if (n + second + third) > (first + second + third) {
window_increases += 1;
}
}
// would have forgotten this if not for the warning triggered by "let mut" without mutation
prev = (prev.1, prev.2, Some(n));
}
println!("One: {}", single_increases);
println!("Two: {}", window_increases);
Ok(())
}

View File

@ -1,14 +1,30 @@
use std::time::{Instant};
use color_eyre::eyre;
mod lib;
use lib::load;
mod day2;
fn main() -> eyre::Result<()> {
let data = load("data/02.txt")?;
day2::run(&data)
let start = Instant::now();
day2::run(&data)?;
let (dur, unit) = format_ns(start.elapsed().as_nanos());
println!("Completed in {}{}", dur, unit);
Ok(())
}
fn format_ns(ns: u128) -> (u128, &'static str) {
const UNITS: [&str; 4] = ["ns", "us", "ms", "s"];
let mut display_n = ns;
let mut unit_idx = 0;
while display_n > 1000 && unit_idx < 4 {
display_n /= 1000;
unit_idx += 1
}
(display_n, UNITS[unit_idx])
}