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:<
If n < 63, which is a reasonable assumption since you'd run out of memory (unless using an iterator implementation) trying to construct the power set anyway, this is a more concise way to do it. Binary operations are way faster than Math.pow()
and arrays for masks, but somehow Java users are afraid of them...
List list = new ArrayList(originalSet);
int n = list.size();
Set> powerSet = new HashSet>();
for( long i = 0; i < (1 << n); i++) {
Set element = new HashSet();
for( int j = 0; j < n; j++ )
if( (i >> j) % 2 == 1 ) element.add(list.get(j));
powerSet.add(element);
}
return powerSet;