I am coding with java so if you can share code with java it would be nice :)
Lets say I have a group of (1,2,3,4,5) and I want to create all subgroups of this group with maximum size of a given natural number (for example 3).
I have found already a code that returns all subgroups however, in my project my group size can reach up to 40 Therefore I it takes too much time to calculate and its very problematic. I am also preferring it to be a function rather than an object. Efficiency is important as well, 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 have found it here: Obtaining a powerset of a set in Java.
I saw your code and adjusted it a little.
You now enter the maximum size of the inner set and it will be the size of the biggest Set.
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;
}