एक सेट S का पावर सेट, S के सभी उपसमुच्चयों का समुच्चय होता है, जिसमें खाली सेट और S स्वयं शामिल होता है। सेट S के पावर सेट को P(S) से दर्शाया जाता है।
उदाहरण के लिए
यदि S = {x, y, z}, तो उपसमुच्चय हैं -
{
{},
{x},
{y},
{z},
{x, y},
{x, z},
{y, z},
{x, y, z}
}
हमें एक JavaScript फ़ंक्शन लिखना है जो एकमात्र तर्क के रूप में एक सरणी लेता है। फ़ंक्शन को इनपुट सरणी के लिए पावर सेट ढूंढना और वापस करना चाहिए।
उदाहरण
निम्नलिखित कोड देखें:
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));
आउटपुट
कंसोल पर निम्नलिखित आउटपुट प्राप्त होगा:
[
[],
[ 'x' ],
[ 'y' ],
[ 'x', 'y' ],
[ 'z' ],
[ 'x', 'z' ],
[ 'y', 'z' ],
[ 'x', 'y', 'z' ]
]