Skip to content

Instantly share code, notes, and snippets.

@YuJianrong
Created March 9, 2013 03:07
Show Gist options
  • Select an option

  • Save YuJianrong/5122309 to your computer and use it in GitHub Desktop.

Select an option

Save YuJianrong/5122309 to your computer and use it in GitHub Desktop.

Revisions

  1. YuJianrong created this gist Mar 9, 2013.
    22 changes: 22 additions & 0 deletions permutation2.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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]