JavaScript generate random number except some values

后端 未结 13 1641
野性不改
野性不改 2021-01-05 11:26

I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(mi         


        
相关标签:
13条回答
  • 2021-01-05 12:14

    One way, which will maintain the generator's statistical properties, is to generate a number in [1, 18]. Then apply, in this order:

    1. If the number is 8 or more, add 1.

    2. If the number is 15 or more, add 1.

    I'd be reluctant to reject and re-sample as that can cause correlation plains to appear in linear congruential generators.

    0 讨论(0)
提交回复
热议问题