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/Cargo.lock | 7 ++++++ 2024/07/rust/Cargo.toml | 6 ++++++ 2024/07/rust/src/main.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 2024/07/rust/Cargo.lock create mode 100644 2024/07/rust/Cargo.toml create mode 100644 2024/07/rust/src/main.rs (limited to '2024/07/rust') diff --git a/2024/07/rust/Cargo.lock b/2024/07/rust/Cargo.lock new file mode 100644 index 0000000..d1897ed --- /dev/null +++ b/2024/07/rust/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aoc_2024-07" +version = "0.1.0" diff --git a/2024/07/rust/Cargo.toml b/2024/07/rust/Cargo.toml new file mode 100644 index 0000000..c64c1b5 --- /dev/null +++ b/2024/07/rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "aoc_2024-07" +version = "0.1.0" +edition = "2021" + +[dependencies] 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