I have different sets that are named. Each set contains different number of Strings. I want to find out which set intersects with which. I have written the following algorithm(untested)
//initial structure key= set name, value = actual set
Map<String, Set<String>> namedSets = new LinkedHashMap<String, Set<String>>();
//get a list of all sets
List<Set<String>> sets = new ArrayList<Set<String>>(namedSets.values());
List<String> names = new ArrayList<String>(namedSets.keySet());
while (!sets.isEmpty()){
Set<String> examinedSet = sets.remove(0); //remove it because it will be checked sortly.
String name = names.remove(0); //remove its name too.
//check it with remaining sets
for (Set<String> set : sets){
//there are common elements inside the two sets,
if (!Collections.disjoint(examinedSet, set)
addIntersection(name, names.get(names.indexOf(set)));
}
public void addIntersection(name, intersectedName){
if (conflictedSets.containsKey(name){
conflictedSets.get(name).add(intersectedName);
}else{
List<String> intersectedNames = new ArrayList<String>();
intersectedNames.add(intersectedName);
conflictedSets.put(name, intersectedNames);
}
}
I don't like the fact that I have to do this nested loop, although for its iteration it is done for one loop less since the checked name gets removed from the list. Is there a more efficient way? My problem is that I don't wan't to check if they are intersecting but which one is intersecting with which. Is there a more efficient algorithm? }