Skip to content

Instantly share code, notes, and snippets.

@nekoTheShadow
Last active August 29, 2015 14:12
Show Gist options
  • Save nekoTheShadow/c809d7652648522edb5d to your computer and use it in GitHub Desktop.
Save nekoTheShadow/c809d7652648522edb5d to your computer and use it in GitHub Desktop.
process.stdin.resume();
process.stdin.setEncoding('utf8');
permutation = function(ary){
var len = ary.length;
var perms = [ary];
for (var startIdx = 0; startIdx <= len-2; startIdx++){
var tempPerms = [];
perms.forEach(function(perm){
for (var changeIdx = startIdx; changeIdx <= len-1; changeIdx++){
var tempPerm = perm.slice(0);
var tempVal = tempPerm[startIdx];
tempPerm[startIdx] = tempPerm[changeIdx];
tempPerm[changeIdx] = tempVal;
tempPerms.push(tempPerm);
}
});
perms = tempPerms.slice(0);
}
return perms
}
// == main ==
console.log(permutation([1,2,3]));
// [ [ 1, 2, 3 ],
// [ 1, 3, 2 ],
// [ 2, 1, 3 ],
// [ 2, 3, 1 ],
// [ 3, 2, 1 ],
// [ 3, 1, 2 ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment