From 4535a4d3e736e10760521b25a40f0c3cca0a7f75 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Wed, 6 Dec 2023 16:00:49 +0000 Subject: [PATCH] 2023 day6/rust: add solution --- 2023/day6/rust/Cargo.toml | 9 ++++++ 2023/day6/rust/src/main.rs | 64 ++++++++++++++++++++++++++++++++++++++ Cargo.lock | 7 +++++ Cargo.toml | 1 + 4 files changed, 81 insertions(+) create mode 100644 2023/day6/rust/Cargo.toml create mode 100644 2023/day6/rust/src/main.rs diff --git a/2023/day6/rust/Cargo.toml b/2023/day6/rust/Cargo.toml new file mode 100644 index 0000000..16a3866 --- /dev/null +++ b/2023/day6/rust/Cargo.toml @@ -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" } diff --git a/2023/day6/rust/src/main.rs b/2023/day6/rust/src/main.rs new file mode 100644 index 0000000..36cbcf3 --- /dev/null +++ b/2023/day6/rust/src/main.rs @@ -0,0 +1,64 @@ +#![warn(clippy::pedantic)] + +use std::io::stdin; + +fn calculate_score>(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( + times_line: &str, + records_line: &str, + make_numbers: F, +) -> impl Iterator +where + F: Fn(&[&str]) -> Vec, +{ + 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(×, &records, |parts| { + parts.iter().map(|n| n.parse().unwrap()).collect() + })) + ); + + println!( + "{}", + calculate_score(make_races(×, &records, |parts| { + vec![parts.iter().copied().collect::().parse().unwrap()] + })) + ); +} diff --git a/Cargo.lock b/Cargo.lock index 87af957..59845ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -677,6 +677,13 @@ dependencies = [ "aoc", ] +[[package]] +name = "rust_2023_06" +version = "0.1.0" +dependencies = [ + "aoc", +] + [[package]] name = "rustversion" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index 461b612..0885520 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,4 +31,5 @@ members = [ "2023/day2/rust", "2023/day4/rust", "2023/day5/rust", + "2023/day6/rust", ]