From de9edd71ccb7ec5919a64a70afe3592daf94617d Mon Sep 17 00:00:00 2001 From: Bearmine Date: Mon, 16 Jun 2025 11:54:01 -0500 Subject: [PATCH] Cache operator sets --- day_07/src/equation/operator_set.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/day_07/src/equation/operator_set.rs b/day_07/src/equation/operator_set.rs index d8b6815..c291157 100644 --- a/day_07/src/equation/operator_set.rs +++ b/day_07/src/equation/operator_set.rs @@ -1,4 +1,11 @@ +use std::collections::HashMap; use std::collections::HashSet; +use std::sync::{LazyLock, Mutex}; + +type OperatorCache = HashMap>>; + +static OPERATOR_SET_CACHE: LazyLock> = + LazyLock::new(|| Mutex::new(HashMap::new())); fn create_operator_set_recurse( operators_permutation_set: &mut HashSet>, @@ -20,7 +27,20 @@ fn create_operator_set_recurse( } pub fn create_operator_set(num_of_operators: usize) -> HashSet> { + { + // Check cache + if let Some(cached_value) = OPERATOR_SET_CACHE.lock().unwrap().get(&num_of_operators) { + return cached_value.clone(); + } + } let mut operator_sets: HashSet> = HashSet::new(); create_operator_set_recurse(&mut operator_sets, vec![false; num_of_operators]); + { + // Store value in cache + OPERATOR_SET_CACHE + .lock() + .unwrap() + .insert(num_of_operators, operator_sets.clone()); + } operator_sets }