js sorted random array

// Sort 1,
// First, by using the array own sort.
// This method is a random positive or negative to make the contents of the array inside the pairwise comparison is a positive number is the order, reverse order is reverse, random disadvantage of this method is not high, can not be entirely random, because it is twenty-two contrast, the last number in the last more likely
var ARR = [1,2,3,4,5,6,7,8,9]
function foo (ARR) {
var clonearr arr.concat = ( );
clonearr.sort (function (N1, N2) {
return Math.random () - 0.5;
})
return clonearr;
}
the console.log (foo (ARR));
// Sort 2
// second, recursive Comparative function
// recursive adaptive method recursive function, a random number is defined index (because the set rounding down, so the range of 0 to 8) as a random index, then its corresponding array from the number remove pressed into the result array in order to achieve random order, if the definition is determined, if the length cloneArr is empty, then exits the loop, this random good randomness, but not very friendly code performance.
ARR = var [1,2,3,4,5,6,7,8,9]
function foo (ARR) {
var Result = [];
var cloneArr arr.concat = ();

(function () {
IF (! cloneArr.length) {} return
var index = Math.floor (Math.random () * cloneArr.length);
Result = result.concat (cloneArr.splice (index,. 1));
The arguments.callee ();
}) ();
return Result;
}
the console.log (foo (ARR));
// Sort 3
number of random out ramp // index corresponding to a third shuffling algorithm it is to the rear and front arrays each switch, so called shuffling code several high operating efficiency compared to the foregoing, also great randomness. In this highly recommended.
ARR = var [1,2,3,4,5,6,7,8,9,10];
function randSort1 (ARR) {
for (var I = 0, len = arr.length; I <len; I ++) {
var = RAND the parseInt (Math.random () * len);
var ARR TEMP = [RAND];
ARR [RAND] = ARR [I];
ARR [I] = TEMP;
}
return ARR;
}
the console.log (randSort1 (ARR));

Guess you like

Origin www.cnblogs.com/wtdall/p/12099901.html