Nick Heiting
Nick Heiting

Reputation: 75

Confused on how this code to compute the powerset works

I found this function on geeksforgeeks to find all subsets of a given set. I'm just not sure what the if statement in the nested for loop is checking. I understand that its using the bitwise AND operator, but I'm confused as to how it helps know which elements to include or not include during any iteration.

import java.io.IOException; 

public class Main 
{ 
    // Print all subsets of given set[] 
    static void printSubsets(char set[]) 
    { 
        int n = set.length; 

        // Run a loop for printing all 2^n 
        // subsets one by obe 
        for (int i = 0; i < (1<<n); i++) 
        { 
            System.out.print("{ "); 

            // Print current subset 
            for (int j = 0; j < n; j++) 

               //???what is this checking?????
                if ((i & (1 << j)) > 0) 
                    System.out.print(set[j] + " "); 

            System.out.println("}"); 
        } 
    } 

    // Driver code 
    public static void main(String[] args) 
    { 
        char set[] = {'a', 'b', 'c'}; 
        printSubsets(set); 
    } 
} 

Upvotes: 3

Views: 59

Answers (2)

flakes
flakes

Reputation: 23624

If there are three items in a powerset, there are 2^3 combinations.

a, b, c
===
[]
[a]
[b]
[a, b]
[c]
[a, c]
[b, c]
[a, b, c]

What you'll notice is that this follows a binary pattern where each bit is matched with an element from the set. If bit is 0 then the elements are removed from the result.

a, b, c
===
[0, 0, 0] -> [0*a, 0*b, 0*c] = []
[1, 0, 0] -> [1*a, 0*b, 0*c] = [a]
[0, 1, 0] -> [0*a, 1*b, 0*c] = [b]
[1, 1, 0] -> [1*a, 1*b, 0*c] = [a, b]
[0, 0, 1] -> [0*a, 0*b, 1*c] = [c]
[1, 0, 1] -> [1*a, 0*b, 1*c] = [a, c]
[0, 1, 1] -> [0*a, 1*b, 1*c] = [b, c]
[1, 1, 1] -> [1*a, 1*b, 1*c] = [a, b, c]

The line if ((i & (1 << j)) > 0) is used to check the bit in order to filter the result.

Upvotes: 2

MJ Studio
MJ Studio

Reputation: 4611

Just think about the arrange of i in the bit level

if n=3 situation,

i=0,

0 0 0 

is arrangement

i=3,

0 1 1 

is that

i & (1<<j) > 0  

is just check condition about bit level,

it is a kind of masking.

because of n is 3,

the value of j in for loop is 0,1,2.

if i=3 situation,

0 1 1

you can pick only j=0,1

if i=5 situation,

1 0 1 

is arrangement

then you can pick only j=0,2

After above process of i 0...7

you can get all of powerset!

Upvotes: 1

Related Questions