Skip to content

Commit

Permalink
Fix btPowerSet() comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Dec 11, 2018
1 parent da0f97a commit d9946c1
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/algorithms/sets/power-set/btPowerSet.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,23 @@
* @return {*[][]} - All subsets of original set.
*/
function btPowerSetRecursive(originalSet, allSubsets = [[]], currentSubSet = [], startAt = 0) {
// In order to avoid duplication we need to start from next element every time we're forming a
// subset. If we will start from zero then we'll have duplicates like {3, 3, 3}.
// Let's iterate over originalSet elements that may be added to the subset
// without having duplicates. The value of startAt prevents adding the duplicates.
for (let position = startAt; position < originalSet.length; position += 1) {
// Let's push current element to the subset.
// Let's push current element to the subset
currentSubSet.push(originalSet[position]);

// Current subset is already valid so let's memorize it.
// We do array destruction here to save the clone of the currentSubSet.
// We need to save a clone since the original currentSubSet is going to be
// mutated in further recursive calls.
allSubsets.push([...currentSubSet]);
// Let's try to form all other subsets for the current subset.

// Let's try to generate all other subsets for the current subset.
// We're increasing the position by one to avoid duplicates in subset.
btPowerSetRecursive(originalSet, allSubsets, currentSubSet, position + 1);
// BACKTRACK. Exclude last element from the subset and try the next one.

// BACKTRACK. Exclude last element from the subset and try the next valid one.
currentSubSet.pop();
}

Expand Down

0 comments on commit d9946c1

Please sign in to comment.