It is required to generate an array containing six random numbers, and these random numbers cannot be repeated.
(The array contains multiple random numbers, each random number is six digits, and the random numbers in the array are not repeated)
You can refer to the following two codes and combine the two.
//随机六位数
function MathRand()
{
var Num="";
for(var i=0;i<6;i++)
{
Num+=Math.floor(Math.random()*10);
}
}
//不重复随机数组
/* num 要产生多少个随机数
from 产生随机数的最小值
to 产生随机数的最大值 */
function createRandom(num ,from ,to )
{
var arr=[];
for(var i=from;i<=to;i++)
arr.push(i);
arr.sort(function(){
return 0.5-Math.random();
});
arr.length=num;
return arr;
}
function createRandom2(num , from , to)
{
var arr=[];
var json={};
while(arr.length<num)
{
//产生单个随机数
var ranNum=Math.ceil(Math.random()*(to-from))+from;
//通过判断json对象的索引值是否存在 来标记 是否重复
if(!json[ranNum])
{
json[ranNum]=1;
arr.push(ranNum);
}
}
return arr;
}
alert(createRandom2(10,0,50));//生成10个从0-50之间不重复的随机数
This can be done through a recursion. For the convenience of demonstration, I changed it to generate a set of non-repeating positive integer random numbers within 10.
The main method it relies on is the indexOf() method, which is used to find the index of a certain value in the array. If it is not found in the array, -1 is returned.
The code is as follows:
Time will not repeat, and using timestamps to generate random numbers will not repeat either.
And to a certain extent, there is no absolute non-repeating random number in this world, and all combinations are not infinite. Even if all the generated random numbers are stored, and then compared when generated, if they are found to already exist, they will be generated. New random numbers will eventually form an infinite loop when all combinations have been tried. What's more, it's only 6 digits, and there are only 472,392 combinations in total.
Let me give you a simple and easy-to-use one. The above cannot guarantee that it will never be repeated. If it is repeated, remember to buy a lottery ticket.
Math.random().toString(36).slice(2,8)
Non-repetitive random number sequence generation algorithm
I saw an article that is very clever. The results and efficiency can be guaranteed. Use code + comments to implement it:
JS is not well written (escape
Write a loop to generate a random number each time and throw it into the set. When the set is long enough, it will be converted into an array and returned
If the required number in the array is small, you can use the array method to determine it