From f954cdad246104b65259e866b7d02488bad10255 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Sat, 7 Dec 2024 10:14:41 -0600 Subject: [PATCH] Day 7 done --- 2024/rust/src/day7.rs | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/2024/rust/src/day7.rs b/2024/rust/src/day7.rs index 39a8935..bf32c55 100644 --- a/2024/rust/src/day7.rs +++ b/2024/rust/src/day7.rs @@ -5,25 +5,26 @@ pub use crate::prelude::*; fn main() { let input = day_input(7); - show_answers(sum_possibly_valid_tests(&input), 0); + show_answers( + sum_possibly_valid_tests(&input, &add_and_mul), + sum_possibly_valid_tests(&input, &add_and_mul_and_concat), + ); } -fn sum_possibly_valid_tests(input: &str) -> usize { +fn sum_possibly_valid_tests(input: &str, f: &dyn Fn(Vec, &usize) -> Vec) -> 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) + .fold(vec![operands[0]], f) .iter() .any(|n| *n == target) { @@ -42,6 +43,16 @@ fn add_and_mul(lefts: Vec, right: &usize) -> Vec { result } +fn add_and_mul_and_concat(lefts: Vec, right: &usize) -> Vec { + let mut result = vec![]; + for left in lefts { + result.push(left + right); + result.push(left * right); + result.push(format!("{}{}", left, right).parse().unwrap()); + } + result +} + #[cfg(test)] mod tests { use super::*; @@ -58,9 +69,25 @@ mod tests { 161011: 16 10 13 192: 17 8 14 21037: 9 7 18 13 -292: 11 6 16 20" +292: 11 6 16 20", + &add_and_mul ), 3749 - ) + ); + 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", + &add_and_mul_and_concat + ), + 11387 + ); } }