Tập hợp phần tử (power set) của một tập hợp S là tập hợp của tất cả các tập hợp con của S, bao gồm cả tập rỗng và chính S. Tập hợp phần tử của S được ký hiệu là P(S).
Ví dụ:
Nếu S = {x, y, z}, các tập hợp con là:
{ {}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z} }Chúng ta cần viết một hàm JavaScript nhận vào một mảng làm đối số duy nhất. Hàm nên tìm và trả về tập hợp phần tử cho mảng đầu vào.
Ví dụ
Dưới đây là mã nguồn:
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));Kết quả
Đầu ra trên console:
[ [], [ 'x' ], [ 'y' ], [ 'x', 'y' ], [ 'z' ], [ 'x', 'z' ], [ 'y', 'z' ], [ 'x', 'y', 'z' ] ]