Skip to content

Instantly share code, notes, and snippets.

@teyfix
Created June 17, 2021 16:40
Show Gist options
  • Save teyfix/5bfb7caaef663b366ed63e325e73e088 to your computer and use it in GitHub Desktop.
Save teyfix/5bfb7caaef663b366ed63e325e73e088 to your computer and use it in GitHub Desktop.
calculating every possible combinations of a given array
// 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