Answers for "powerset javascript examples"

0

powerset javascript examples

const set = ['x', 'y', 'z'];
const powerSet = (arr = []) => {
   const res = [];
   const { length } = arr;
   const numberOfCombinations = 2 ** length;
   for (let combinationIndex = 0; combinationIndex < numberOfCombinations; combinationIndex += 1) {
      const subSet = [];
      for (let setElementIndex = 0; setElementIndex < arr.length;
      setElementIndex += 1) {
         if (combinationIndex & (1 << setElementIndex)) {
            subSet.push(arr[setElementIndex]);
         };
      };
      res.push(subSet);
   };
   return res;
};
console.log(powerSet(set));
Posted by: Guest on June-29-2021
0

powerset JavaScript

function powerSet(arr) {
  
  // the final power set
  var powers = [];
  
  // the total number of sets that the power set will contain
  var total = Math.pow(2, arr.length);
  
  // loop through each value from 0 to 2^n
  for (var i = 0; i < total; i++) {
    
    // our set that we add to the power set
    var tempSet = [];
    
    // convert the integer to binary
    var num = i.toString(2);
    
    // pad the binary number so 1 becomes 001 for example
    while (num.length < arr.length) { num = '0' + num; }
    
    // build the set that matches the 1's in the binary number
    for (var b = 0; b < num.length; b++) {
      if (num[b] === '1') { tempSet.push(arr[b]); }    
    }
    
    // add this set to the final power set
    powers.push(tempSet);
    
  }
  
  return powers;
  
}

powerSet([1, 2, 3]);
Posted by: Guest on June-29-2021

Code answers related to "powerset javascript examples"

Code answers related to "Javascript"

Browse Popular Code Answers by Language