Created
July 7, 2019 00:12
-
-
Save morulus/adf085c50c40397abba138269d7f411c to your computer and use it in GitHub Desktop.
Generate possible combinations of letters (Javascript)
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
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