I have set
{A,B,C,D,E}
And I have a map (someMapWithSets in the code example) of sets which indicates if elements are compatible:
A: B,C - (means A is compatible with B and C and etc)
B: A,E,C
C: A,B
D: E
E: B,D
I need to have a map of sets where all possible combinations of compatible elements are present (largest set possible) with values like (don't care about key):
A,B,C
B,E
D,E
So as I part of the solution I thought I could create a method that retains only compatible elements for the given set and chosen element.
public static Map<String, Set<String>> defineCompatibility(Set<String> set) {
if (set.isEmpty()) {
return new HashMap<>();
}
Map<String, Set<String>> finalResult = new HashMap<>();
Set<String> elementsToDefine = new HashSet<>(set);
while (!elementsToDefine.isEmpty()) {
String currentElement = elementsToDefine.stream().findFirst().get();
Set<String> definedSet = defineForElement(set, currentElement);
finalResult.put(currentElement, definedSet);
elementsToDefine.remove(currentElement);
}
return finalResult;
}
private static Set<String> defineForElement(Set<String> set, String rootElement) {
Set<String> result = someMapWithSets.get(rootElement);
result.retainAll(set);
result.add(rootElement);
Set<String> tmpHolder = new HashSet<>(result);
for (String next : tmpHolder) {
if (!result.contains(next)) {
break;
}
Set<String> strings = someMapWithSets.get(next);
strings.add(next);
result.retainAll(strings);
}
return result;
}
But this code does not work properly because it is not capable to define all possible combinations, only a few of them. I've tried to store data about elements that were not processed but the code became very complex to be understandable.
I am stuck with implementation. Please help. Maybe there is some well-known algorithm for this task? Thank you.