Skip to content
Advertisement

Power set of an input set as custom collection

I have been reading the Effective Java book and I have stuck with this code I am unable to understand how this code is generating power set.

Code:

JavaScript

Output:

JavaScript

Can someone explain how this code is generating powerset of a given set.

Advertisement

Answer

The code uses the binary representation of the index number as a map of which element of s to include.

For instance, assuming only 3 bits in a number:

JavaScript

The get method of the generated list follows this logic with the index input given:

  • index >>= 1 shifts all bits one position to the right with each loop
  • (index & 1) == 1 checks whether the rightmost bit of index is a 1

The & operator is the binary AND, so 2 & 1 equals binary 010 AND 001, giving 000 (not equal to 1 or 001) and 3 & 1 equals binary 011 AND 001, giving 001 (equal to 1 or 001)

  • If this evaluates to true, the i-th element is added to the list
  • This terminates when index == 0, i.e. there are no more bits to shift / elements to add

Example for index = 3:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement