Files
adventofcode2024/day_07/src/equation/operator_set.rs

47 lines
1.3 KiB
Rust
Raw Normal View History

2025-06-16 11:54:01 -05:00
use std::collections::HashMap;
2025-06-16 11:32:05 -05:00
use std::collections::HashSet;
2025-06-16 11:54:01 -05:00
use std::sync::{LazyLock, Mutex};
type OperatorCache = HashMap<usize, HashSet<Vec<bool>>>;
static OPERATOR_SET_CACHE: LazyLock<Mutex<OperatorCache>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
2025-06-16 11:32:05 -05:00
fn create_operator_set_recurse(
operators_permutation_set: &mut HashSet<Vec<bool>>,
operators: Vec<bool>,
) {
operators_permutation_set.insert(operators.clone());
if !operators.contains(&false) {
return;
}
for i in 0..operators.len() {
if operators[i] {
continue;
}
let mut new_operators = operators.clone();
new_operators[i] = true;
create_operator_set_recurse(operators_permutation_set, new_operators);
}
}
pub fn create_operator_set(num_of_operators: usize) -> HashSet<Vec<bool>> {
2025-06-16 11:54:01 -05:00
{
// Check cache
if let Some(cached_value) = OPERATOR_SET_CACHE.lock().unwrap().get(&num_of_operators) {
return cached_value.clone();
}
}
2025-06-16 11:32:05 -05:00
let mut operator_sets: HashSet<Vec<bool>> = HashSet::new();
create_operator_set_recurse(&mut operator_sets, vec![false; num_of_operators]);
2025-06-16 11:54:01 -05:00
{
// Store value in cache
OPERATOR_SET_CACHE
.lock()
.unwrap()
.insert(num_of_operators, operator_sets.clone());
}
2025-06-16 11:32:05 -05:00
operator_sets
}