Skip to content

Instantly share code, notes, and snippets.

@es
Created December 21, 2013 22:49
Show Gist options
  • Save es/8076209 to your computer and use it in GitHub Desktop.
Save es/8076209 to your computer and use it in GitHub Desktop.
Returns an array with all the permutations of the array passed.
function permutate (arr) {
var permutations = [];
function helper (list, perm) {
var currentLength = perm.length;
if (perm.length === arr.length) {
return permutations.push(perm);
}
else {
for (var i = 0, len = list.length; i < len; i++) {
perm[currentLength] = list[i];
var tempArr = list.slice(0);
tempArr.splice(i, 1);
helper(tempArr, perm.slice(0));
}
}
}
helper(arr, []);
return permutations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment