Skip to content

Instantly share code, notes, and snippets.

@YuJianrong
Created March 9, 2013 03:07
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 YuJianrong/5122309 to your computer and use it in GitHub Desktop.
Save YuJianrong/5122309 to your computer and use it in GitHub Desktop.
Get permutation from the index of the permutation.
var x=[1,2,3,4,5,6];
function factorial(i) {
if (!factorial.memorize[i]) {
factorial.memorize[i] = i * factorial(i-1);
}
return factorial.memorize[i];
}
factorial.memorize = {0:1};
function perm(arr, index) {
for(var start = 0; start<arr.length; ++start) {
var fac = factorial(arr.length - start -1),
swapIndex = Math.floor( index / fac );
var swapElement = arr.splice( swapIndex + start , 1)[0];
arr.splice(start, 0 , swapElement);
index = index % fac;
}
}
perm(x,0); // x keeps [1,2,3,4,5,6]
perm(x,719); // x changed to [6,5,4,3,2,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment