I am trying to get a powerset (all subsets of a set) in Java. So my logic for that is:
- A given set is one subset, so add so it as it is to result.
- Remove each element of set from given set and we will get all the combinations for 1 element less. Add these results to final result.
- Recursively find subsets of all sets from step 2 and add to result.
I tried searching for a similar solution on Stack Overflow but did not get one. Is this a clean way to implement it?
import java.util.*;
public class PowerSet {
public static <E> Set<Set<E>> findPowerSet(Set<E> set){
Set<Set<E>> ret = new HashSet<Set<E>>();
ret.add(set);
if(set.isEmpty()){
return ret;
}
Iterator<E> it = set.iterator();
while(it.hasNext()){
Set<E> tmp = new HashSet<E>(set); //create a copy of current set
tmp.remove(it.next()); //remove current element from copy set
ret.add(tmp); //add the remaining set to result
ret.addAll(findPowerSet(tmp)); //recursively find subsets of copy set
}
return ret;
}
public static void main(String[] args) {
Set<Character> set = new HashSet<Character>();
set.add('a');set.add('b');set.add('c');
System.out.println("Input set"); printSet(set);
System.out.println("\nsub sets");
findPowerSet(set).stream().forEach(PowerSet::printSet);
}
public static <E> void printSet(Set<E> set){
StringBuilder sb = new StringBuilder(set.size()==0 ? "{}\n" :"{");
Iterator<E> it = set.iterator();
while(it.hasNext()){
sb.append(it.next().toString())
.append(it.hasNext()? ", " : "}\n");
}
System.out.print(sb.toString());
}
}