Skip to content

Commit 47dda38

Browse files
committed
add iterative approach
1 parent 731c735 commit 47dda38

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Recursion/powerset.js

+30
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,33 @@ const subsets = getPowerSet(array);
7777
subsets.forEach((subset) => {
7878
console.log(subset);
7979
});
80+
81+
// Iterative approach
82+
function powersetIterative(array) {
83+
// Initialize the powerset with the empty subset
84+
let subset = [[]];
85+
86+
// Iterate over each element in the input array
87+
for (let ele of array) {
88+
// Get the current length of the subset
89+
let length = subset.length;
90+
91+
// Iterate over each existing subset
92+
for (let i = 0; i < length; i++) {
93+
// Get the current subset
94+
let currentSubset = subset[i];
95+
96+
// Create a new subset by making a copy of the current subset
97+
let newSubset = [...currentSubset];
98+
99+
// Add the current element to the new subset
100+
newSubset.push(ele);
101+
102+
// Append the new subset to the powerset
103+
subset.push(newSubset);
104+
}
105+
}
106+
107+
// Return the powerset
108+
return subset;
109+
}

0 commit comments

Comments
 (0)