Despite reading a lot of Q/A about permutation/combination: Finding All Combinations of JavaScript array values + JavaScript - Generating combinations from n arrays with m elements I have not found the right way to get the kind of result I'm looking for. I got a 10 values array:
var arr = [0,1,2,3,4,5,6,7,8,9];
If I'm right, the number of all possible permuted arrays of unique values (no duplicates):
[5,9,1,8,2,6,7,0,4,3] [4,8,0,2,1,9,7,3,6,5] ...
is 2x3x4x5x6x7x8x9x10 = 3628800
I'm trying to produce a function to dynamically create the 'n' array. For example:
function createArray(0) -> [0,1,2,3,4,5,6,7,8,9]
function createArray(45648) -> [0,1,5,3,2,8,7,9,6] (something like...)
function createArray(3628800) -> [9,8,7,6,5,4,3,2,1,0]
The way I'm figuring to achieve it is:
createArray(1) permutes the 2 last signs (8,9 -> 9,8)
createArray(2->6) permutes the 3 last signs (8,7,9 -> 9,8,7)
createArray(3628800) : all values are permuted (9->0)
Do you think it's possible/easy to do, and if yes how to proceed ?
[EDIT]
Thanks for helpfull answers
function permute(permutation, val) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p,
n = 0;
while (i < length) {
if (c[i] < i) {
if (n <= val) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
if (n == val) {
arr = permutation.slice();
console.log("n="+n+"\n"+arr);
console.log( 'Duration: '+((new Date() - t1)/1000)+'s' );
break;
}
else { n+=1; }
}
} else {
c[i] = 0;
++i;
}
}
}
let t1 = new Date();
permute([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 100000); // <- array requested
console : n=100000 + 0,5,8,1,7,2,3,6,4,9 + Duration: 0.004s