arrays - Find ith permutation in javascript -
given array arr
of size n
, , and index 0<i<n!
want return ith permutation.
i able write method gets permutations:
function permute (arr) { var permutations = []; if (arr.length === 1) { return [ arr ]; } (var = 0; < arr.length; i++) { var subperms = permute(arr.slice(0, i).concat(arr.slice(i + 1))); (var j = 0; j < subperms.length; j++) { subperms[j].unshift(arr[i]); permutations.push(subperms[j]); } } return permutations; }
how trim 1 branch of recursion ?
you use factorial of length of array helper getting wanted permutation.
basically algorithm calculates indices of array , reassembles result upon.
function getn(n, array) { var f, l = array.length, indices = []; array = array.slice(); while (l--) { f = factorial(l); indices.push(math.floor(n / f)); n %= f; } return indices.map(function (i) { return array.splice(i, 1)[0]; }); } function factorial(num) { var result = 1; while (num) { result *= num; num--; } return result; } var i, l, array = [1, 2, 3, 4]; (i = 0, l = factorial(array.length); < l; i++) { console.log(i, getn(i, array).join(' ')); }
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment