Node: Generate 6 digits random number using crypto.randomBytes

前端 未结 6 1427
陌清茗
陌清茗 2020-12-16 20:44

What is the correct way to generate exact value from 0 to 999999 randomly since 1000000 is not a power of 2?

This is my approa

6条回答
  •  庸人自扰
    2020-12-16 21:06

    I call it the random_6d algo. Worst case just a single additional loop.

    var random_6d = function(n2){
        var n1 = crypto.randomBytes(3).readUIntLE(0, 3) >>> 4;
    
        if(n1 < 1000000)
            return n1;
    
        if(typeof n2 === 'undefined')
            return random_6d(n1);
    
        return Math.abs(n1 - n2);
    };
    

    loop version:

    var random_6d = function(){
        var n1, n2;
    
        while(true){
            n1 = crypto.randomBytes(3).readUIntLE(0, 3) >>> 4;
    
            if(n1 < 1000000)
                return n1;
    
            if(typeof n2 === 'undefined')
                n2 = n1;
            else
                return Math.abs(n1 - n2);
        };
    };
    

提交回复
热议问题