From 4619aaf4ed5fce80d6c3c38522d3a2fa7ddecc47 Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Tue, 10 Dec 2024 16:21:03 +0100 Subject: [PATCH] day 7: part 2: rust --- 2024/days/07/part2/Cargo.toml | 6 ++++ 2024/days/07/part2/src/main.rs | 53 ++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 2024/days/07/part2/Cargo.toml create mode 100644 2024/days/07/part2/src/main.rs diff --git a/2024/days/07/part2/Cargo.toml b/2024/days/07/part2/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2024/days/07/part2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/days/07/part2/src/main.rs b/2024/days/07/part2/src/main.rs new file mode 100644 index 0000000..5970209 --- /dev/null +++ b/2024/days/07/part2/src/main.rs @@ -0,0 +1,53 @@ + +fn concatenate_integers(a: u64, b: u64) -> u64 { + let a_str = a.to_string(); + let b_str = b.to_string(); + let result_str = a_str + &b_str; + let result: u64 = result_str.parse().unwrap(); + return result; +} + +fn can_be_evaluated_to_aux(operands: &Vec, target: u64, current: u64, index: usize) -> bool { + if index == 0 { + return can_be_evaluated_to_aux(operands, target, operands[0], index + 1); + } else if index == operands.len() { + if current == target { + return true; + } else { + return false; + } + } else { + return + can_be_evaluated_to_aux(operands, target, current * operands[index], index + 1) + || can_be_evaluated_to_aux(operands, target, current + operands[index], index + 1) + || can_be_evaluated_to_aux(operands, target, concatenate_integers(current, operands[index]), index + 1) + ; + } +} + +fn can_be_evaluated_to(operands: &Vec, target: u64) -> bool { + return can_be_evaluated_to_aux(operands, target, 0, 0); +} + +fn main() -> std::io::Result<()> { + let mut total: u64 = 0; + for line in std::io::stdin().lines() { + let line = line.unwrap(); + if line != "".to_string() { + let mut parts = line.split(":"); + let target = parts.next().unwrap(); + let target = target.parse::().unwrap(); + let operands: Vec = parts.next() + .unwrap() + .split(" ") + .skip(1) + .map(|e| e.parse::().unwrap()) + .collect(); + if can_be_evaluated_to(&operands, target) { + total += target; + } + } + } + println!("{}", total); + Ok(()) +}