Skip to content

Instantly share code, notes, and snippets.

@morulus
Created July 7, 2019 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morulus/adf085c50c40397abba138269d7f411c to your computer and use it in GitHub Desktop.
Save morulus/adf085c50c40397abba138269d7f411c to your computer and use it in GitHub Desktop.
Generate possible combinations of letters (Javascript)
module.exports = function getCombinations(letters, count, shift = 0) {
let variants = [];
for (let i = shift; i < letters.length; i++) {
if (count > 1) {
const childCombinations = getCombinations(letters, count - 1, i + 1);
for (let c = 0; c < childCombinations.length; c++) {
variants.push([letters[i]].concat(childCombinations[c]));
}
} else {
variants.push([letters[i]])
}
}
return variants;
}
/*
Example:
getCombinations('abc', 2);
Result: [ [ 'a', 'b' ], [ 'a', 'c' ], [ 'b', 'c' ] ]
// 5 ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment