2023: Day 6, part 1

This commit is contained in:
Wesley Moore 2023-12-06 17:50:26 +10:00
parent 83fd0b4b9c
commit f202587c42
No known key found for this signature in database
5 changed files with 74 additions and 0 deletions

7
2023/day6/Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day6"
version = "0.1.0"

8
2023/day6/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "day6"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

54
2023/day6/src/main.rs Normal file
View file

@ -0,0 +1,54 @@
use std::{env, fs};
type BoxError = Box<dyn std::error::Error>;
fn main() -> Result<(), BoxError> {
let input_path = env::args_os()
.skip(1)
.next()
.ok_or("missing input file path")?;
let input = fs::read_to_string(input_path)?;
let mut lines = input.lines();
let times = lines.next().ok_or("missing times")?;
let distances = lines.next().ok_or("missing distances")?;
let times = parse("Time:", times)?;
let distances = parse("Distance:", distances)?;
if times.len() != distances.len() {
return Err("time/distance length mismatch".into());
}
let mut results = vec![0; times.len()];
for (i, (time, record_distance)) in times
.iter()
.copied()
.zip(distances.iter().copied())
.enumerate()
{
(1..time - 1).for_each(|hold| {
let velocity = hold;
let distance = (time - hold) * velocity;
if distance > record_distance {
results[i] += 1;
}
})
}
println!("Part 1: {}", results.iter().fold(1, |a, b| a * b));
Ok(())
}
fn parse(prefix: &str, line: &str) -> Result<Vec<usize>, BoxError> {
if !line.starts_with(prefix) {
return Err(format!("line did not match expected prefix ({}): {}", prefix, line).into());
}
let numbers = line
.split_ascii_whitespace()
.skip(1)
.filter(|word| !word.is_empty())
.map(|word| word.parse::<usize>())
.collect::<Result<Vec<_>, _>>()?;
Ok(numbers)
}

3
2023/input/day6.sample Normal file
View file

@ -0,0 +1,3 @@
Time: 7 15 30
Distance: 9 40 200

2
2023/input/day6.txt Normal file
View file

@ -0,0 +1,2 @@
Time: 60 80 86 76
Distance: 601 1163 1559 1300