Write a program to generate Powerset of a set in Java. A power set of a set S is the set of all possible subsets of S, including the empty set and S itself.

For example, for set {a, b, c}, the subsets are:

  • {} (empty set)
  • {a}
  • {b}
  • {c}
  • {a, b}
  • {a, c}
  • {b, c}
  • {a, b, c}

and hence the power set of S is {{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}}.

 
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.

Download Code

Output:

[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]

 

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. For instance, for set {a, b, c}, we generate binary numbers from 0 to 23-1, and for each number generated, the corresponding set can be found by considering set bits in the number, as shown below:

  • 0 = 000 = {}
  • 1 = 001 = {c}
  • 2 = 010 = {b}
  • 3 = 011 = {b, c}
  • 4 = 100 = {a}
  • 5 = 101 = {a, c}
  • 6 = 110 = {a, b}
  • 7 = 111 = {a, b, c}

Download Code

Output:

[]
[1]
[2]
[1, 2]

That’s all about generating the powerset of a Set in Java.

 
Reference: https://en.wikipedia.org/wiki/Power_set