Better permutation creation
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -57,3 +57,27 @@ pub fn create_operator_set(num_of_operators: usize) -> HashSet<Vec<Op>> {
|
||||
|
||||
operator_sets
|
||||
}
|
||||
|
||||
fn create_permutations_recurse(
|
||||
values: &HashSet<Op>,
|
||||
len: usize,
|
||||
permutations: &mut HashSet<Vec<Op>>,
|
||||
curr_permutation: Vec<Op>,
|
||||
) {
|
||||
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<Op>, len: usize) -> HashSet<Vec<Op>> {
|
||||
let mut permutations = HashSet::new();
|
||||
create_permutations_recurse(&set, len, &mut permutations, vec![]);
|
||||
permutations
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user