Generate A Weighted Random Number

前端 未结 11 2218
予麋鹿
予麋鹿 2020-11-22 12:40

I\'m trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the

11条回答
  •  情话喂你
    2020-11-22 12:49

    I use the following

    function weightedRandom(min, max) {
      return Math.round(max / (Math.random() * max + min));
    }
    

    This is my go-to "weighted" random, where I use an inverse function of "x" (where x is a random between min and max) to generate a weighted result, where the minimum is the most heavy element, and the maximum the lightest (least chances of getting the result)

    So basically, using weightedRandom(1, 5) means the chances of getting a 1 are higher than a 2 which are higher than a 3, which are higher than a 4, which are higher than a 5.

    Might not be useful for your use case but probably useful for people googling this same question.

    After a 100 iterations try, it gave me:

    ==================
    | Result | Times |
    ==================
    |      1 |    55 |
    |      2 |    28 |
    |      3 |     8 |
    |      4 |     7 |
    |      5 |     2 |
    ==================
    

提交回复
热议问题