Created
September 13, 2013 16:23
-
-
Save mcsheffrey/6552844 to your computer and use it in GitHub Desktop.
Permute array and return array of permutations
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
var temp = []; | |
var answer = []; | |
return doIt(arr); | |
function doIt(a) { | |
var i, len, item; | |
for (i = 0, len = arr.length; i < len; i++) { | |
// remove the item at index i | |
console.log(i); | |
item = arr.splice(i, 1)[0]; | |
// add that item to the array we're building up | |
temp.push(item); | |
if (arr.length) { | |
// if there's still anything left in the array, | |
// recurse over what's left | |
doIt(arr); | |
} else { | |
// otherwise, log the result and move on | |
logResult(); | |
} | |
// restore the item we removed at index i | |
// and remove it from our temp array | |
arr.splice(i, 0, item); | |
temp.pop(); | |
} | |
return answer; | |
} | |
function logResult() { | |
answer.push( | |
// make a copy of temp using .slice() | |
// so we can continue to work with temp | |
temp.slice() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment