Confused on how this code to compute the powerset works

Nick Heiting :

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); 
    } 
} 
flakes :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98629&siteId=1