Skip to content

Instantly share code, notes, and snippets.

@williscool
Forked from md2perpe/permutations.js
Last active January 21, 2017 04:42
Show Gist options
  • Save williscool/2cadbde4a0386db81271 to your computer and use it in GitHub Desktop.
Save williscool/2cadbde4a0386db81271 to your computer and use it in GitHub Desktop.
Function for generating permutations of a list.
// permutations(["c","a","t"])
function permutations(array){
if (array.length === 0) return [[]];
var perms = [];
for(var i = 0; i < array.length; i++) {
var copy = array.slice(0);
var prefix = copy.splice(i,1);
var rest = permutations(copy);
for(var j = 0; j < rest.length ; j++) {
perms.push(prefix.concat(rest[j]));
}
}
return perms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment