2023 day6/rust: add solution

This commit is contained in:
Xiretza 2023-12-06 16:00:49 +00:00
parent f618e1620d
commit 4535a4d3e7
4 changed files with 81 additions and 0 deletions

View file

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

View file

@ -0,0 +1,64 @@
#![warn(clippy::pedantic)]
use std::io::stdin;
fn calculate_score<I: IntoIterator<Item = (u64, u64)>>(races: I) -> u64 {
races
.into_iter()
.map(|(t, r)| {
// x(t-x) = r
// tx-x^2 = r
// x^2-tx+r = 0
// [ x^2+px+q = 0 ==> x = -p/2±sqrt((p/2)^2-q) ]
// x = t/2 ± sqrt(t^2/4-r)
#[allow(clippy::cast_precision_loss)]
let t = t as f64;
#[allow(clippy::cast_precision_loss)]
let r = r as f64;
let v = t / 2.0;
let w = (t.powi(2) / 4.0 - r).sqrt();
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
((v - w + 1.0).floor() as u64, (v + w - 1.0).ceil() as u64)
})
.map(|(min, max)| max - min + 1)
.product()
}
fn make_races<F>(
times_line: &str,
records_line: &str,
make_numbers: F,
) -> impl Iterator<Item = (u64, u64)>
where
F: Fn(&[&str]) -> Vec<u64>,
{
let do_line = |line: &str| {
let parts: Vec<_> = line.split(' ').filter(|s| !s.is_empty()).skip(1).collect();
make_numbers(&parts)
};
do_line(times_line).into_iter().zip(do_line(records_line))
}
fn main() {
let mut lines = stdin().lines().map(Result::unwrap);
let times = lines.next().unwrap();
let records = lines.next().unwrap();
println!(
"{}",
calculate_score(make_races(&times, &records, |parts| {
parts.iter().map(|n| n.parse().unwrap()).collect()
}))
);
println!(
"{}",
calculate_score(make_races(&times, &records, |parts| {
vec![parts.iter().copied().collect::<String>().parse().unwrap()]
}))
);
}

7
Cargo.lock generated
View file

@ -677,6 +677,13 @@ dependencies = [
"aoc",
]
[[package]]
name = "rust_2023_06"
version = "0.1.0"
dependencies = [
"aoc",
]
[[package]]
name = "rustversion"
version = "1.0.11"

View file

@ -31,4 +31,5 @@ members = [
"2023/day2/rust",
"2023/day4/rust",
"2023/day5/rust",
"2023/day6/rust",
]