1

This is based on a previous SO post. Here I don't understand how the** if(i & Math.pow(2, j)** part is used to select the array element. The code is pasted below.

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 read the answers and Mathematically I get it is using & operator and checking if it is 0 or 1, but I don't understand the logic behind it. Please can someone explain it?

Ananth_
  • 33
  • 3
  • What exactly do you not understand form [this answer](https://stackoverflow.com/a/47802203/1048572)? To me, it sounds like you're asking exactly the same question again. – Bergi Mar 30 '23 at 10:58
  • Did you try stepping through the code with a debugger? – Bergi Mar 30 '23 at 10:58

0 Answers0