generate random numbers within a range with different probabilities

前端 未结 6 1083
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 07:05

How can i generate a random number between A = 1 and B = 10 where each number has a different probability?

Example: number / probability

1 - 20%

2 -

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 07:30

    Here's an implementation of Knuth's Algorithm. As discussed by some of the answers it works by 1) creating a table of summed frequencies 2) generates a random integer 3) rounds it with ceiling function 4) finds the "summed" range within which the random number falls and outputs original array entity based on it

提交回复
热议问题