Home  >  Q&A  >  body text

javascript - How to generate a set of non-repeating six-digit random numbers

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之间不重复的随机数
过去多啦不再A梦过去多啦不再A梦2710 days ago1433

reply all(6)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:41:10

    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:

    var arr=[];
    function getRandom(){
        var random=Math.floor(Math.random()*1000000);
        console.log(random);
        //判断生成的数在数组中是否存在,判断是否是6位数
        //如果不存在而且是6位数,放入数组
        if(random.toString().length==6&&arr.indexOf(random)==-1){     
            arr.push(random)
        }else{
        //如果存在或者不是6位数,接着调用这个函数,生成满足要求的随机数
            console.log("不符合要求的"+random)
            getRandom();
        }
    }
    for(var i=0;i<6;i++){
        getRandom();
    }
    console.log(arr);

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:41:10

    Time will not repeat, and using timestamps to generate random numbers will not repeat either.

    console.log((Math.random() * Date.now()).toFixed(0));
    // 6位的
    console.log((Math.random() * Date.now() / 1000000).toFixed(0));

    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.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:41:10

    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)

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:41:10

    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:

    function getRandom(numCount) {
            var numList = [];
            var numMin = 100000;
            var numMax = 999999;
            var listLen = numMax - numMin + 1;
    
            var outPut = [];
    
            // 将所有数顺序装填到数字列表中
            for (var i = numMin; i < numMax + 1; i++) {
                numList.push(i);
            }
    
            var randNum;
            for (var j = 0; j < numCount; j++) {
                // 产生一个小于列表长度的随机数randNum
                randNum = Math.floor(Math.random() * listLen);
                // 将列表的第randNum项输出
                outPut.push(numList[randNum]);
                // 将列表的最后一项替换到刚被取出的数的位置
                numList[randNum] = numList[listLen - 1];
                // 列表长度减一,即列表最后一项不会再被取到;
                listLen--;
            }
    
            return outPut;
        }
        var arr = getRandom(30);
        console.log(arr);

    JS is not well written (escape

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:41:10

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:41:10

    If the required number in the array is small, you can use the array method to determine it

    console.time('time:');
    function createRandomArr(l){
        var r = [];
        var o = {};
        var a;
        for (var i = 0;i < l;i++){
            a = Math.random().toString().slice(2,8);
            o[a] ? i-- : (r.push(a),o[a] = true);
        }
        return r;
    }
    var res = createRandomArr(10000);
    console.log(res,res.length);
    console.timeEnd("time:");

    reply
    0
  • Cancelreply