diff options
author | mhsn <mail@mhsn.net> | 2025-08-20 12:23:05 +0100 |
---|---|---|
committer | mhsn <mail@mhsn.net> | 2025-08-20 12:23:05 +0100 |
commit | 5ee08cbb28fd70c52b088f68c4d56be3816cdb73 (patch) | |
tree | f42ef11b2834b38459eb725ca0b8f6b0f45804f2 /2024/07/rust/src/main.rs | |
parent | 6483ca70089f359e93a38ac6564bac1ebd7a1f42 (diff) | |
download | aoc-5ee08cbb28fd70c52b088f68c4d56be3816cdb73.tar.gz aoc-5ee08cbb28fd70c52b088f68c4d56be3816cdb73.zip |
rust 2024 07: refactor
Diffstat (limited to '2024/07/rust/src/main.rs')
-rw-r--r-- | 2024/07/rust/src/main.rs | 58 |
1 files changed, 37 insertions, 21 deletions
diff --git a/2024/07/rust/src/main.rs b/2024/07/rust/src/main.rs index 07fef57..df586b1 100644 --- a/2024/07/rust/src/main.rs +++ b/2024/07/rust/src/main.rs @@ -17,17 +17,8 @@ fn main() -> io::Result<()> { }) .collect::<Vec<_>>(); - 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(); + let silver: u64 = eqns.iter().map(crate::silver).sum(); + let gold: u64 = eqns.iter().map(crate::gold).sum(); println!("silver: {silver}"); println!("gold: {gold}"); @@ -39,17 +30,42 @@ 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; +fn calibration(want: u64, x: &u64, y: &u64, rest: &[u64], gold: bool) -> bool { + if *x > want { + return false; + } + match rest { + [] => want == x + y || want == x * y || (gold && want == concat(x, y)), + [z, rest @ ..] => { + calibration(want, &(x + y), z, rest, gold) + || calibration(want, &(x * y), z, rest, gold) + || (gold && calibration(want, &concat(x, y), z, rest, gold)) + } + } +} + +fn silver((want, nums): &(u64, Vec<u64>)) -> u64 { + match nums.as_slice() { + [x, y, rest @ ..] => { + if calibration(*want, x, y, rest, false) { + *want + } else { + 0 + } + } + _ => 0, + } +} + +fn gold((want, nums): &(u64, Vec<u64>)) -> u64 { + match nums.as_slice() { + [x, y, rest @ ..] => { + if calibration(*want, x, y, rest, true) { + *want + } else { + 0 } - calibration(want, &[&[x + y], xs].concat(), gold) || - calibration(want, &[&[x * y], xs].concat(), gold) || - (gold && calibration(want, &[&[concat(x, y)], xs].concat(), gold) ) } + _ => 0, } } |