在JavaScript Power Set中查找集合的功率集
集合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' ] ]