I have a set of characters {'p', 'q', 'r', ...}
and I want to call run()
(not important what that does) on all permutations of mappings from the characters to boolean values. For example, if my set of characters was {'p','q','r'}
and I naively went through every permutation manually, it would look like this:
private static void runMaps(){
HashMap<Character,Boolean> m = new HashMap<>();
m.put('p', true);
m.put('q', true);
m.put('r', true);
run(m);
m = new HashMap<>();
m.put('p', true);
m.put('q', true);
m.put('r', false);
run(m);
// ...
// 8 permutations
}
It's bugging me because I know I can (and should be able to) use recursion here but I'm struggling.
Edit: After a while I managed to get it working. There's some added stuff in the code below but the general idea is shown.
private static boolean runMaps(SyntaxTree formula, ArrayList<String> chars, HashMap<String, Boolean> map, int index) {
if (index == chars.size()) {
return checkFormula(formula, map).getData().equals("true");
} else {
HashMap<String, Boolean> newMap1 = (HashMap<String, Boolean>) map.clone();
newMap1.put(chars.get(index), true);
HashMap<String, Boolean> newMap2 = (HashMap<String, Boolean>) map.clone();
newMap2.put(chars.get(index), false);
return runMaps(formula, chars, newMap1, index + 1) && runMaps(formula, chars, newMap2, index + 1);
}
}