A little context, I was looking at another SO post when I am trying to solve javascript problem to find all possible subsets. I am not asking about the JS challenge, but why it was there and what mathematical significance does it have?
Here is the copy paste of the code from this SO post
var arr = [1, 2, 3];
function generatePowerSet(array) {
var result = [];
result.push([]);
for (var i = 1; i < Math.pow(2, array.length); i++, result.push(subset))
for (var j = 0, subset = []; j < array.length; j++)
if (i & Math.pow(2, j))
subset.push(array[j]);
return result;
}
console.log(generatePowerSet(arr));
I don't understand what is being accomplished by if (i & Math.pow(2, j))
line. The mozilla doc says that it performs AND comparison on each bits pair. Why is it relevant?
What I mean when I say relevant, for example with LEFT SHIFT, doing a << 1 multiples a by two. Its equivalent mathematical function is multiplying by two if a << b
and b is 1
. I don't understand what mathematical function &
does in this case.