From 81337c405ba39568a8e5bfaaf72e14b53bc967c9 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Sat, 7 Dec 2024 10:10:48 -0600 Subject: [PATCH] Day 7 part 1 --- 2024/rust/src/day7.rs | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 2024/rust/src/day7.rs diff --git a/2024/rust/src/day7.rs b/2024/rust/src/day7.rs new file mode 100644 index 0000000..39a8935 --- /dev/null +++ b/2024/rust/src/day7.rs @@ -0,0 +1,66 @@ +mod prelude; +use std::slice::Windows; + +pub use crate::prelude::*; + +fn main() { + let input = day_input(7); + show_answers(sum_possibly_valid_tests(&input), 0); +} + +fn sum_possibly_valid_tests(input: &str) -> usize { + let mut sum = 0; + for l in input.lines() { + let (target, operands) = l.split_once(':').unwrap(); + let target: usize = target.parse().unwrap(); + println!("{target}"); + let operands: Vec = operands + .trim() + .split(" ") + .map(|s| s.parse().unwrap()) + .collect(); + println!("{operands:?}"); + if operands + .iter() + .skip(1) + .fold(vec![operands[0]], add_and_mul) + .iter() + .any(|n| *n == target) + { + sum += target; + } + } + sum +} + +fn add_and_mul(lefts: Vec, right: &usize) -> Vec { + let mut result = vec![]; + for left in lefts { + result.push(left + right); + result.push(left * right); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + assert_eq!( + sum_possibly_valid_tests( + "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" + ), + 3749 + ) + } +}