How to choose randomly in a certain ratio

前端 未结 5 579
醉话见心
醉话见心 2021-01-06 15:10

I want to choose randomly* between two alternatives with unequal probability.

For instance, when the user presses a button, 25% of the time it would make sound A and

5条回答
  •  醉梦人生
    2021-01-06 15:27

    The ration 3:5 is equivalent to 37.5% of the time or 0.375 (3 times it's A, 5 times it's B, so 3/8 is 37.5%). So you can calculate it like this:

    random() < 0.375 ? "A" : "B"
    

    From

    http://en.wikipedia.org/wiki/Ratio

    If there are 2 oranges and 3 apples, the ratio of oranges to apples is shown as 2:3, whereas the fraction of oranges to total fruit is 2/5.

提交回复
热议问题