In this question The intersection of all combinations of n
sets a method based on Map#reduce
is presented to obtain all intersections of n
sets. My question is, is there such a way to find the union of n
sets?
This is what I have done, but it is very slow for a large number of sets:
public static void main(String[] args) {
List<List<Set<Integer>>> unionSet = new ArrayList<>();
List<List<Integer>> sets = ...
double avail = 0;
for (int i = 1; i <= sets.size(); i++) {
List<Set<Integer>> us = new ArrayList<>();
union(sets, us, new HashSet<>(), i, 0);
unionSet.add(us);
}
}
public static void union(List<List<Integer>> sets, List<Set<Integer>> unionSet,
Set<Integer> set, int size, int index) {
for (int i = index; i < sets.size(); i++) {
Set temp = new HashSet(set);
temp.addAll(set.get(i));
if (size != 1)
union(sets, unionSet, temp, size - 1, i + 1);
else
unionSet.add(temp);
}
}
question from:
https://stackoverflow.com/questions/65914891/the-union-of-all-combinations-of-n-sets 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…