Created
December 21, 2013 22:49
-
-
Save es/8076209 to your computer and use it in GitHub Desktop.
Returns an array with all the permutations of the array passed.
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
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