เซตกำลังของเซต 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' ] ]