Created
June 17, 2021 16:40
-
-
Save teyfix/5bfb7caaef663b366ed63e325e73e088 to your computer and use it in GitHub Desktop.
calculating every possible combinations of a given array
This file contains hidden or 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
// credit: https://codesandbox.io/s/all-combinations-of-words-v14d9 | |
function combinations(words: string[]): string[][] { | |
const combs: string[][] = [[]]; | |
for (const word of words) { | |
combs.push( | |
...combs.map((comb) => { | |
return [...comb, word]; | |
}) | |
); | |
} | |
return combs; | |
} | |
console.log(combinations(["1"])); | |
console.log(combinations(["1", "2"])); | |
console.log(combinations(["1", "2", "3"])); | |
function combinationsRecursive(words: string[]): string[][] { | |
if (words.length === 0) { | |
return [[]]; | |
} | |
const base = combinationsRecursive(words.slice(0, -1)); | |
const wordToAdd = words[words.length - 1]; | |
const allCombinations = [...base]; | |
for (const baseCombination of base) { | |
allCombinations.push([...baseCombination, wordToAdd]); | |
} | |
return allCombinations; | |
} | |
console.log(combinationsRecursive(["1"])); | |
console.log(combinationsRecursive(["1", "2"])); | |
console.log(combinationsRecursive(["1", "2", "3"])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment