From c82296633a0fa896d0c05415f2ee8f6d62b29150 Mon Sep 17 00:00:00 2001 From: Reiner Herrmann Date: Sat, 7 Dec 2024 20:58:16 +0100 Subject: day7 solution 1 --- src/bin/day7.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/bin/day7.rs diff --git a/src/bin/day7.rs b/src/bin/day7.rs new file mode 100644 index 0000000..60b08b1 --- /dev/null +++ b/src/bin/day7.rs @@ -0,0 +1,50 @@ +static DAY: u8 = 7; + +fn main() { + let input = advent::read_lines(DAY); + println!("{DAY}a: {}", calibration_result(&input)); + println!("{DAY}b: {}", 0); +} + +fn calculateable(result: i64, operands: &[i64]) -> bool { + if operands.len() == 1 { + return result == operands[0]; + } + let rem = &operands[..=operands.len()-2]; + let op = operands[operands.len()-1]; + calculateable(result - op, rem) || (result % op == 0 && calculateable(result / op, rem)) +} + +fn calibration_result(input: &[String]) -> i64 { + let mut sum = 0; + for line in input { + let (result, operands) = line.split_once(": ").unwrap(); + let result = result.parse::().unwrap(); + let operands = operands.split(" ").map(|x| x.parse::().unwrap()).collect::>(); + if calculateable(result, &operands) { + sum += result; + } + } + sum +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + let input = [ + "190: 10 19", + "3267: 81 40 27", + "83: 17 5", + "156: 15 6", + "7290: 6 8 6 15", + "161011: 16 10 13", + "192: 17 8 14", + "21037: 9 7 18 13", + "292: 11 6 16 20", + ].iter().map(|&x| String::from(x)).collect::>(); + assert_eq!(calibration_result(&input), 3749); + } +} -- cgit v1.2.3