In JavaScript, the usual random numbers are duplicated, but sometimes we need random numbers that are not repeated, how do we implement them? Here are three ways to produce random numbers that are not duplicated, and compare them to see how efficient they are.
Method One
Idea: first create an array of 1 to 3000, take one number at a time, and then remove the number taken out of the array, so that you can never repeat it.
Copy 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); Randomly take a position
document.write (index+ ",");
Originalarray.splice (index,1);
}
var d2=new Date (). GetTime ();
document.write ("Operation time consuming" + (D2-D1));
</script>
Performance: Takes 1528 milliseconds.
Method Two
Idea: To improve the efficiency by improving the slice method of method one. Or take a number out of the original array, and then assign this position of the original array to null. The next time the count is taken, it is null, and if it is null, it is not taken.
Copy 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 consuming" + (D2-D1));
</script>
Performance: Takes 290 milliseconds.
Method Three
Train of thought: Break the original array, and then output sequentially, this can also be done randomly never repeat, and more efficient.
Copy 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 consuming" + (D2-D1));
</script>
Performance: Takes 229 milliseconds.
Through the performance analysis, it is concluded that the method three is the best scheme.