Вопрос

I got an algorithm whose objective is to give all possible sums of all combinations in an array of Integer.

private void arraySumPermutation(int value ,int[] arr){
    int N = arr.length;     
    for(int i=0;i<1<<N;i++){
        int sum = 0;                
        for(int j=0;j<N;j++){       

            if((i & 1<<j)>0){
                iCount++;
                sum += arr[j];  
                //S.O.P(sum);
            }
        }

    }
}

I am not able to understand the inner if condition added with bitwise AND. What is the objective of inner if loop.

if((i & 1<<j)>0)
Это было полезно?

Решение

Let's represent cominations of N-element set as N-bit numbers, where jth bit is 1 if jth item is included in the combintation, and 0 otherwise. This way you can represent all possible combinations as numbers in range [0, 2N).

The outer loop iterates over these numbers (1 << N == 2N).

The inner loop iterates over items of the set and if condition checks whether jth item is included into the current combination. In other words, it checks if jth bit of i is 1.

1<<j gives you a number where only jth bit is 1, i & (1 << j) resets all bits of i other than that bit, and > checks that result is not 0.

Note that this code (with ints) only works for N < 31.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top