Calculating the number of possible permutations for an array of length n is crucial. It can be achieved using the formula n! (n factorial).
function factorial(n){ return n<=0?1:n*factorial(n-1);}
//Other methods may exist, but this is a basic example
We can also generate a function that associates an integer p within the range of 0 to n!-1 with a unique permutation.
function map(p,orgArr){
var tempArr=orgArr.slice(); //Make a copy
var l=orgArr.length;
var permArr=[];
var pick;
do{
pick=p%l; //using mod operator
permArr.push(tempArr.splice(pick,1)[0]); //Taking item at index 'pick' from old array and adding it to new array
p=(p-pick)/l;
l--;
}while(l>=1)
return permArr;
}
To proceed, you just need to create an array
ordering=[0,1,2,3,...,factorial(n)-1]
and shuffle it. Next, loop through
for(var i=0;i<=ordering.length;i++) doSomething(map(ordering[i],YourArray));
The remaining task is shuffling the ordering array. This process has extensive documentation available and varies based on specific requirements like randomness or cryptographic strength. Refer to resources such as How to randomize (shuffle) a JavaScript array? for assistance.
In cases where creating a large ordering array is impractical due to the high number of permutations, selectively choosing values of i in the loop between 0 and n!-1 becomes necessary. For simple uniformity requirements, primitive roots can serve as a viable solution: http://en.wikipedia.org/wiki/Primitive_root_modulo_n