diff --git a/day_07/src/equation.rs b/day_07/src/equation.rs index 5acf723..2549c3f 100644 --- a/day_07/src/equation.rs +++ b/day_07/src/equation.rs @@ -48,10 +48,6 @@ impl Equation { self.answer } - pub fn components(&self) -> &Vec { - &self.components - } - fn compute_answer(&self, operators: &[Op]) -> i64 { let mut accumulator = self.components[0]; @@ -59,6 +55,11 @@ impl Equation { match op { Op::Multiply => accumulator *= self.components[i + 1], Op::Add => accumulator += self.components[i + 1], + Op::CONCAT => { + let accumulator_string = format!("{}", accumulator); + let component_string = format!("{}", self.components[i + 1]); + accumulator = (accumulator_string + &component_string).parse().unwrap(); + } } } @@ -78,4 +79,18 @@ impl Equation { } false } + + pub fn solvable_multiply_add_concat(&self) -> bool { + let op_combinations = create_permutations( + HashSet::from([Op::Add, Op::Multiply, Op::CONCAT]), + self.components.len() - 1, + ); + + for combination in op_combinations { + if self.answer == self.compute_answer(&combination) { + return true; + } + } + false + } } diff --git a/day_07/src/equation/operator_set.rs b/day_07/src/equation/operator_set.rs index f1ce173..f9a5a1c 100644 --- a/day_07/src/equation/operator_set.rs +++ b/day_07/src/equation/operator_set.rs @@ -1,13 +1,15 @@ -use std::collections::HashMap; use std::collections::HashSet; -use std::sync::{LazyLock, Mutex}; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Op { Multiply, Add, + CONCAT, } +// use std::collections::HashMap; +// use std::sync::{LazyLock, Mutex}; + // type OperatorCache = HashMap>>; // static OPERATOR_SET_CACHE: LazyLock> = diff --git a/day_07/src/main.rs b/day_07/src/main.rs index 0d642ac..df6176b 100644 --- a/day_07/src/main.rs +++ b/day_07/src/main.rs @@ -33,19 +33,34 @@ fn main() -> Result<(), Box> { equations.push(Equation::new(&line)?) } - let mut value_sum = 0; + let mut result_add_multiply = 0; + let mut result_add_multiply_concat = 0; println!("Is solvable?"); println!("------------"); for equation in equations { - let solvable = equation.solvable_multiply_add(); - println!("{:?} => {}", equation, solvable); - if solvable { - value_sum += equation.answer(); + let solvable_add_multiply = equation.solvable_multiply_add(); + let solvable_add_multiply_concat = equation.solvable_multiply_add_concat(); + println!( + "{:?} => {} | {}", + equation, solvable_add_multiply, solvable_add_multiply_concat + ); + if solvable_add_multiply { + result_add_multiply += equation.answer(); + } + if solvable_add_multiply_concat { + result_add_multiply_concat += equation.answer(); } } - println!("\n Total Calibration Result: {}", value_sum); + println!( + "\n Total Calibration Result (ADD|MULTIPLY): {}", + result_add_multiply + ); + println!( + "\n Total Calibration Result (ADD|MULTIPLY|CONCAT): {}", + result_add_multiply_concat + ); Ok(()) }