Details can be explained with reference to other articles, I have here is reverse Cantor Cantor expansion and deployment JavaScript implementation.
Code:
/ * Full permutation hash - (Cantor Cantor Expand Expand and inverse) Cantor Expandable:! X = a [n] * (n-1) + a [n-1] * (n-2) +! A + ... [I] * (I-1)! + ... + A [1] * 0! * e.g. * is defined as 0 2,3 * 3,2 is defined as 1 * 2, 3 is defined as 2 * 2,3,1 defined as 3 * 3,1,2 defined as 4 * 3,2,1 defined as 5 * * / // factorial function FAC (X) { the let ANS. 1 = ; for (I = 2 the let; I <= X; I ++) { ANS * = I; } return ANS; } // Cantor expand: the whole arrangement of a one, it returns an integer representing the ranking of all permutations Cantor function (A) { const = n-a.length; the let ANS = 0; for (the let I = 0; I <n-; I ++) { the let TEMP = 0; for (the let = I + J. 1; J <n-; j ++) { IF (A [J] <A [I]) TEMP ++ ; } ans += temp * fac(n - i - 1); } return ans; } //逆康托展开 function decantor( x, oa) { const a=[].concat(oa).sort(function (n,m) { return n-m; }) const na=[] const n=a.length; let temp; let used=[]; let i,j; for(i=0;i<n;i++){ temp= (x/fac(n-i-1))>>0 for( j=0;j<n;j++){ if(!used[j]){ if(temp===0)break; --temp; } } na[i]=a[j]; used[j]=true; x=x%fac(n-i-1); } return na; }
test:
//测试 const arr1=[5,2,3,4] for(let i=0;i<fac(arr1.length);i++){ const arr=decantor(i,arr1); console.log(cantor(arr)) console.log(arr) } //结果 "C:\Program Files\nodejs\node.exe" D:\test\Cantor.js 0 [ 2, 3, 4, 5 ] 1 [ 2, 3, 5, 4 ] 2 [ 2, 4, 3, 5 ] 3 [ 2, 4, 5, 3 ] 4 [ 2, 5, 3, 4 ] 5 [ 2, 5, 4, 3 ] 6 [ 3, 2, 4, 5 ] 7 [ 3, 2, 5, 4 ] 8 [ 3, 4, 2, 5 ] 9 [ 3, 4, 5, 2 ] 10 [ 3, 5, 2, 4 ] 11 [ 3, 5, 4, 2 ] 12 [ 4, 2, 3, 5 ] 13 [ 4, 2, 5, 3 ] 14 [ 4, 3, 2, 5 ] 15 [ 4, 3, 5, 2 ] 16 [ 4, 5, 2, 3 ] 17 [ 4, 5, 3, 2 ] 18 [ 5, 2, 3, 4 ] 19 [ 5, 2, 4, 3 ] 20 [ 5, 3, 2, 4 ] 21 [ 5, 3, 4, 2 ] 22 [ 5, 4, 2, 3 ] 23 [ 5, 4, 3, 2 ] Process finished with exit code 0