Created
December 16, 2017 11:18
-
-
Save antelle/e2e035abb49d0c99692d9f2734a924f5 to your computer and use it in GitHub Desktop.
Combinations & Permutations in JS
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
let numbers = '1 2 3'.split(' ').map(n => +n); | |
getCombinations([], numbers, x => console.log('C', x.join(' '))); | |
getPermutations([], numbers, x => console.log('P', x.join(' '))); | |
function getCombinations(first, chars, cb) { | |
for (var i = 0; i < chars.length; i++) { | |
cb(first.concat(chars[i])); | |
getCombinations(first.concat(chars[i]), chars.slice(i + 1), cb); | |
} | |
} | |
function getPermutations(first, chars, cb) { | |
for (var i = 0; i < chars.length; i++) { | |
cb(first.concat(chars[i])); | |
getPermutations(first.concat(chars[i]), chars.slice(0, i).concat(chars.slice(i + 1)), cb); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment