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.
The expression i & Math.pow(2, j) gives a non-zero value when the jth bit in i is 1 (counting from the least significant bit, which is the 0th bit).
This can be best explained by example. Let's say i is 10 at a certain moment; in binary: 1010. Now let j be 0. Then:
i & Math.pow(2, j)
== 10 & Math.pow(2, 0)
== 10 & 1
== 0b1010 & 0b0001
== 0b0000
The effect of the second value (0b0001) is filtering: it filters out exactly one bit from the first value. See what happens when j is 1:
i & Math.pow(2, j)
== 10 & Math.pow(2, 1)
== 10 & 2
== 0b1010 & 0b0010
== 0b0010
The if condition will thus be true for this value of j.
As i has two 1 bits, there will be two times that the if condition is true for that particular value of i.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With