Is there a function to find all subgroups from one main group by filtering certain subgroups?
I’m writing code in java, so it would be great if you could share code with java 🙂
Let’s say I have a group (1,2,3,4,5) and I want to create all subgroups of the group with a maximum size of a given natural number (e.g. 3).
I’ve found a code that returns all subgroups, however, in my project my group size can be up to 40, so I need to spend too much time calculating and it’s very problematic. I also prefer it to be a function rather than an object. Efficiency is also important, I can’t create all possible groups and then filter them out.
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<>();
if (originalSet.isEmpty()) {
sets.add(new HashSet<>());
return sets;
}
List<T> list = new ArrayList<>(originalSet);
T head = list.get(0);
Set<T> rest = new HashSet<>(list.subList(1, list.size()));
for (Set<T> set : powerSet(rest)) {
Set<T> newSet = new HashSet<>();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
return sets;
}
I found it here:
Obtaining a powerset of a set in Java .
Solution
I looked at your code and tweaked it slightly.
You now enter the maximum size of the inner collection, which will be the size of the largest collection.
public static <T> Set<Set<T>> powerSet(Set<T> originalSet, int size) {
Set<Set<T>> sets = new HashSet<>();
if (originalSet.isEmpty()) {
sets.add(new HashSet<>());
return sets;
}
List<T> list = new ArrayList<>(originalSet);
T head = list.get(0);
Set<T> rest = new HashSet<>(list.subList(1, list.size()));
for (Set<T> set : powerSet(rest, size)) {
if(set.size() <= size-1 ){
Set<T> newSet = new HashSet<>();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
}
return sets;
}