Node: Generate 6 digits random number using crypto.randomBytes

前端 未结 6 1428
陌清茗
陌清茗 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:33

    It's a correct algorithm (https://en.wikipedia.org/wiki/Rejection_sampling), though you could consider using bitwise operations instead of converting to hex. It can run forever if the random number generator is malfunctioning -- you could consider trying a fixed number of times and then throwing an exception instead of looping forever.

提交回复
热议问题