Created
April 4, 2022 13:05
-
-
Save oitee/169425e332476b3ec952da323006eb57 to your computer and use it in GitHub Desktop.
A JS implementation of powerSet, using tail recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//[...] =>[[], []] | |
// [] => [[]] | |
// [1] => [[], [1]] | |
// [1, 2] => [[], [1]] + [2] + [1, 2] | |
// [1, 2, 3] => [[], [1], [2], [1, 2]] + [3] + [1, 3] + [ 1, 2] + [1, 2, 3] | |
function powerSet(arr) { | |
if (arr.length === 0) { | |
return [[]]; | |
} | |
let lastItem = arr.pop(); | |
let res = powerSet(arr); | |
newRes = res.map((itemArr) => { | |
// this is to create a clone of the array to prevent mutation of the elements of the original array `res` | |
let currentArr = itemArr.slice(); | |
currentArr.push(lastItem); | |
return currentArr; | |
}); | |
return res.concat(newRes); | |
} | |
function powerSetTailRecursive(arr, acc = [[]]) { | |
if (arr.length === 0) { | |
return acc; | |
} | |
let lastItem = arr.pop(); | |
let newAcc = acc.map(itemArr => { | |
let currentArr = itemArr.slice(); | |
currentArr.push(lastItem) | |
return currentArr | |
}) | |
newAcc = acc.concat(newAcc); | |
return powerSetTailRecursive(arr, newAcc); | |
} | |
console.log(powerSet([1, 2, 3])); | |
console.log(powerSetTailRecursive([1, 2, 3])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment