Generate random integers with probabilities

前端 未结 5 840
离开以前
离开以前 2020-11-30 02:27

I\'m a bit confused about how to generate integer values with probabilities.

As an example, I have four integers with their probability values: 1|0.4, 2|0.3, 3|0.2,

5条回答
  •  天命终不由人
    2020-11-30 03:24

    Here's a useful trick :-)

    function randomWithProbability() {
      var notRandomNumbers = [1, 1, 1, 1, 2, 2, 2, 3, 3, 4];
      var idx = Math.floor(Math.random() * notRandomNumbers.length);
      return notRandomNumbers[idx];
    }
    

提交回复
热议问题