In JavaScript, random numbers are usually generated repeatedly, but sometimes we need random numbers that are not repeated. How can we achieve this? The following describes three methods to generate random numbers that are not repeated and compare them. The efficiency of this method is high.
Method 1
Idea: first create an array ranging from 1 to 3000, fetch a number each time, and then remove the number from the array, so that it can never be repeated.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var count = 3000;
Var originalArray = new Array; // original Array
// Assign a value to the original array originalArray
For (var I = 0; I <count; I ++ ){
OriginalArray [I] = I + 1;
}
Var d1 = new Date (). getTime ();
For (I = 0; I <count; I ++ ){
Var index = Math. floor (Math. random () * originalArray. length); // random location
Document. write (index + ",");
OriginalArray. splice (index, 1 );
}
Var d2 = new Date (). getTime ();
Document. write ("Operation Time consumed" + (d2-d1 ));
</Script>
Performance: It takes 1528 milliseconds.
Method 2
Idea: Improve the slice Method of method 1 to improve efficiency. Or retrieve a number from the original array and assign a null value to the position of the original array. Determines whether the value is null in the next fetch. If the value is null, no value is obtained.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var count = 3000;
Var originalArray = new Array; // original Array
// Assign a value to the original array originalArray
For (var I = 0; I <count; I ++ ){
OriginalArray [I] = I + 1;
}
Var d1 = new Date (). getTime ();
For (var num, I = 0; I <count; I ++ ){
Do {
Num = Math. floor (Math. random () * count );
} While (originalArray [num] = null );
Document. write (originalArray [num] + ",");
OriginalArray [num] = null;
}
Var d2 = new Date (). getTime ();
Document. write ("Operation Time consumed" + (d2-d1 ));
</Script>
Performance: It takes 290 milliseconds.
Method 3
Train of Thought: scatter the original array and then output it in sequence. In this way, the random array can never be repeated and the efficiency is higher.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var count = 3000;
Var originalArray = new Array; // original Array
// Assign a value to the original array originalArray
For (var I = 0; I <count; I ++ ){
OriginalArray [I] = I + 1;
}
Var d1 = new Date (). getTime ();
OriginalArray. sort (function () {return 0.5-Math. random ();});
For (var I = 0; I <count; I ++ ){
Document. write (originalArray [I] + ",");
}
Var d2 = new Date (). getTime ();
Document. write ("Operation Time consumed" + (d2-d1 ));
</Script>
Performance: It takes 229 milliseconds.
Through performance analysis, method 3 is the best solution.