집합 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' ] ]