Fix btPowerSet() comments.

This commit is contained in:
Oleksii Trekhleb 2018-12-11 07:57:38 +02:00
parent da0f97a2d3
commit d9946c1249

View File

@ -6,16 +6,23 @@
* @return {*[][]} - All subsets of original set. * @return {*[][]} - All subsets of original set.
*/ */
function btPowerSetRecursive(originalSet, allSubsets = [[]], currentSubSet = [], startAt = 0) { 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 // Let's iterate over originalSet elements that may be added to the subset
// subset. If we will start from zero then we'll have duplicates like {3, 3, 3}. // without having duplicates. The value of startAt prevents adding the duplicates.
for (let position = startAt; position < originalSet.length; position += 1) { 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]); currentSubSet.push(originalSet[position]);
// Current subset is already valid so let's memorize it. // 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]); 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); 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(); currentSubSet.pop();
} }