Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created September 13, 2013 16:23
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 mcsheffrey/6552844 to your computer and use it in GitHub Desktop.
Save mcsheffrey/6552844 to your computer and use it in GitHub Desktop.
Permute array and return array of permutations
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