Skip to content

Instantly share code, notes, and snippets.

@antelle
Created December 16, 2017 11:18
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 antelle/e2e035abb49d0c99692d9f2734a924f5 to your computer and use it in GitHub Desktop.
Save antelle/e2e035abb49d0c99692d9f2734a924f5 to your computer and use it in GitHub Desktop.
Combinations & Permutations in JS
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