Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining a powerset of a set in Java

The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let's say I have a Set in Java:

Set<Integer> mySet = new HashSet<Integer>(); mySet.add(1); mySet.add(2); mySet.add(3); Set<Set<Integer>> powerSet = getPowerset(mySet); 

How do I write the function getPowerset, with the best possible order of complexity? (I think it might be O(2^n).)

like image 492
Manuel Araoz Avatar asked Nov 03 '09 23:11

Manuel Araoz


People also ask

How do you calculate Powerset in Java?

The simplest solution is to use the Guava library. The powerSet() method provided by the Sets class calculates all possible subsets of the specified set. Another approach to find Powerset is to generate all binary numbers between 0 and 2n-1 , where n is the size of the specified set.

How do you create a subset of a set in Java?

The subSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. The set returned by this method is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.

How do you create a power set of a set?

To create the Power Set, write down the sequence of binary numbers (using n digits), and then let "1" mean "put the matching member into this subset". Well, they are not in a pretty order, but they are all there.


1 Answers

Yes, it is O(2^n) indeed, since you need to generate, well, 2^n possible combinations. Here's a working implementation, using generics and sets:

public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {     Set<Set<T>> sets = new HashSet<Set<T>>();     if (originalSet.isEmpty()) {         sets.add(new HashSet<T>());         return sets;     }     List<T> list = new ArrayList<T>(originalSet);     T head = list.get(0);     Set<T> rest = new HashSet<T>(list.subList(1, list.size()));      for (Set<T> set : powerSet(rest)) {         Set<T> newSet = new HashSet<T>();         newSet.add(head);         newSet.addAll(set);         sets.add(newSet);         sets.add(set);     }            return sets; }   

And a test, given your example input:

 Set<Integer> mySet = new HashSet<Integer>();  mySet.add(1);  mySet.add(2);  mySet.add(3);  for (Set<Integer> s : SetUtils.powerSet(mySet)) {      System.out.println(s);  } 
like image 62
João Silva Avatar answered Oct 12 '22 02:10

João Silva