From 6483ca70089f359e93a38ac6564bac1ebd7a1f42 Mon Sep 17 00:00:00 2001 From: mhsn Date: Wed, 20 Aug 2025 11:57:53 +0100 Subject: 2024-07 rust p1,p2 --- 2024/07/rust/src/main.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2024/07/rust/src/main.rs (limited to '2024/07/rust/src') diff --git a/2024/07/rust/src/main.rs b/2024/07/rust/src/main.rs new file mode 100644 index 0000000..07fef57 --- /dev/null +++ b/2024/07/rust/src/main.rs @@ -0,0 +1,55 @@ +use std::io; + +fn main() -> io::Result<()> { + let eqns = io::stdin() + .lines() + .flatten() + .collect::>() + .iter() + .map(|line| line.split_once(": ").unwrap()) + .map(|(ans, nums)| { + ( + ans.parse::().unwrap(), + nums.split_whitespace() + .map(|s| s.parse::().unwrap()) + .collect::>(), + ) + }) + .collect::>(); + + let silver: u64 = eqns + .iter() + .filter(|(ans, nums)| calibration(ans, nums, false)) + .map(|(ans, _)| ans) + .sum(); + + let gold: u64 = eqns + .iter() + .filter(|(ans, nums)| calibration(ans, nums, true)) + .map(|(ans, _)| ans) + .sum(); + + println!("silver: {silver}"); + println!("gold: {gold}"); + + return Ok(()); +} + +fn concat(x: &u64, y: &u64) -> u64 { + x * (10u64.pow(y.ilog10() + 1)) + y +} + +fn calibration(want: &u64, nums: &[u64], gold: bool) -> bool { + match nums { + [] => unreachable!(), + [x] => want == x, + [x, y, xs @ ..] => { + if x > want { + return false; + } + calibration(want, &[&[x + y], xs].concat(), gold) || + calibration(want, &[&[x * y], xs].concat(), gold) || + (gold && calibration(want, &[&[concat(x, y)], xs].concat(), gold) ) + } + } +} -- cgit v1.2.3