From e2cb8390863b7b2aa7bf4270ef9112da908bdfbf Mon Sep 17 00:00:00 2001 From: Bearmine Date: Mon, 16 Jun 2025 12:58:38 -0500 Subject: [PATCH] Better permutation creation --- day_07/src/equation.rs | 11 +++++++++-- day_07/src/equation/operator_set.rs | 24 ++++++++++++++++++++++++ day_07/src/main.rs | 2 +- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/day_07/src/equation.rs b/day_07/src/equation.rs index f704598..c1aceb0 100644 --- a/day_07/src/equation.rs +++ b/day_07/src/equation.rs @@ -1,7 +1,11 @@ mod operator_set; +use std::collections::HashSet; + use operator_set::{Op, create_operator_set}; +use crate::equation::operator_set::create_permutations; + #[derive(Debug)] pub struct Equation { answer: i64, @@ -63,8 +67,11 @@ impl Equation { accumulator } - pub fn solvable(&self) -> bool { - let op_combinations = create_operator_set(self.components.len() - 1); + pub fn solvable_multiply_add(&self) -> bool { + let op_combinations = create_permutations( + HashSet::from([Op::Add, Op::Multiply]), + self.components.len() - 1, + ); for combination in op_combinations { if self.answer == self.compute_answer(&combination) { diff --git a/day_07/src/equation/operator_set.rs b/day_07/src/equation/operator_set.rs index 3d79cd8..7fd3bac 100644 --- a/day_07/src/equation/operator_set.rs +++ b/day_07/src/equation/operator_set.rs @@ -57,3 +57,27 @@ pub fn create_operator_set(num_of_operators: usize) -> HashSet> { operator_sets } + +fn create_permutations_recurse( + values: &HashSet, + len: usize, + permutations: &mut HashSet>, + curr_permutation: Vec, +) { + if curr_permutation.len() == len { + permutations.insert(curr_permutation); + return; + } + + for v in values { + let mut next_permutation = curr_permutation.clone(); + next_permutation.push(*v); + create_permutations_recurse(values, len, permutations, next_permutation); + } +} + +pub fn create_permutations(set: HashSet, len: usize) -> HashSet> { + let mut permutations = HashSet::new(); + create_permutations_recurse(&set, len, &mut permutations, vec![]); + permutations +} diff --git a/day_07/src/main.rs b/day_07/src/main.rs index 92a3fc3..0d642ac 100644 --- a/day_07/src/main.rs +++ b/day_07/src/main.rs @@ -38,7 +38,7 @@ fn main() -> Result<(), Box> { println!("Is solvable?"); println!("------------"); for equation in equations { - let solvable = equation.solvable(); + let solvable = equation.solvable_multiply_add(); println!("{:?} => {}", equation, solvable); if solvable { value_sum += equation.answer();