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 ifjth 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
ifcondition checks whetherjth item is included into the current combination. In other words, it checks ifjth bit ofiis 1.1<<jgives you a number where onlyjth bit is 1,i & (1 << j)resets all bits ofiother than that bit, and>checks that result is not 0.Note that this code (with
ints) only works for N < 31.