Finding power set for a set in JavaScript Power Set


The power set of a set S is the set of all of the subsets of S, including the empty set and S itself. The power set of set S is denoted as P(S).

For example

If S = {x, y, z}, the subsets are −

{
   {},
   {x},
   {y},
   {z},
   {x, y},
   {x, z},
   {y, z},
   {x, y, z}
}

We are required to write a JavaScript function that takes in an array as the only argument. The function should find and return the power set for the input array.

Example

Following is the code −

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));

Output

Following is the output on console −

[
   [],
   [ 'x' ],
   [ 'y' ],
   [ 'x', 'y' ],
   [ 'z' ],
   [ 'x', 'z' ],
   [ 'y', 'z' ],
   [ 'x', 'y', 'z' ]
]

Updated on: 11-Dec-2020

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements