How to choose randomly in a certain ratio

前端 未结 5 612
醉话见心
醉话见心 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:22

    For 3:5 you can add them together to get 8, and pick a random integer less than 8. If it's 0, 1, or 2 (three chances) you choose A, and if it's 3, 4, 5, 6, or 7 (five chances) you choose B. Code-wise you'd just check whether your random number is less than 3.

    For something like 3:5:4, you'd pick a random number less than 12 (3+5+4) and if it's less than 3 you choose A, otherwise if it's less than 8 (3+5) you choose B, otherwise you choose C.

    This can generalize to any number of alternatives, but it's inefficient with lots of alternatives since you have to check the random number against each threshold, which is O(n). This SO question seems to provide some more efficient (but more complex) algorithms for weighted random selection with larger numbers of alternatives.

提交回复
热议问题