
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' ] ]
- Related Articles
- Power Set
- Power Set in Lexicographic order in C++
- Javascript search for an object key in a set
- Creating a Set using Javascript
- Check for Power of two in JavaScript
- Finding the power of a string from a string with repeated letters in JavaScript
- Validating a power JavaScript
- Set Data Structure in Javascript
- The Set Class in Javascript
- Arrays vs Set in JavaScript.
- JavaScript Set Date Methods
- Ways to create a Set in JavaScript?
- Loop through a Set using Javascript
- How to set a default parameter value for a JavaScript function?
- Set a bit for BigInteger in Java

Advertisements