In JavaScript, the usual random numbers are duplicated, but sometimes we need random numbers that don't repeat, how do we do that? This article gives a solution to the needs of friends can refer to the next
In JavaScript, the random numbers that are normally generated are duplicated, but sometimes we need random numbers that don't repeat, how do we do that? Here are three ways to generate non-repetitive random numbers and compare them to see how efficient that method is.
Method One
Idea: first create an array of 1 to 3000, take one number at a time, and then remove this number from the array, so you can never repeat it.
Copy the Code code as follows:
<script type= "Text/javascript" >
var count=3000;
var originalarray=new array;//Original Array
Assigning values 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); Take a random position
document.write (index+ ",");
Originalarray.splice (index,1);
}
var d2=new Date (). GetTime ();
document.write ("Operation Time" + (D2-D1));
</script>
Performance: Takes 1528 milliseconds.
Method Two
Idea: The slice method of method one is improved to improve the efficiency. Or remove a number from the original array, and then assign NULL to this position of the original array. The next time the number is taken, the judgment is null, and if NULL is not taken.
Copy the Code code as follows:
<script type= "Text/javascript" >
var count=3000;
var originalarray=new array;//Original Array
Assigning values 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" + (D2-D1));
</script>
Performance: Takes 290 milliseconds.
Method Three
Idea: Break the original array and then output it in turn, so that it can be random and never repeat, and more efficient.
Copy the Code code as follows:
<script type= "Text/javascript" >
var count=3000;
var originalarray=new array;//Original Array
Assigning values 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" + (D2-D1));
</script>
Performance: Takes 229 milliseconds.
Through the performance analysis, the method three is the best solution.
JavaScript produces non-repeating random number three ways to realize the idea