JavaScript 中的冪集發現集合的冪集


集合 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' ]
]

更新日期:11-12-2020

699 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.