How to choose randomly in a certain ratio

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

    Assuming your random number generator gives back a double value between 0.0 and 1.0, you just do a comparison to the exact ratio you want. In the case of 3 out of 5, you'd check to see if the random value was less than 0.6.

    if(rand < 0.6) {
        playSound(A);
    }
    else {
        playSound(B);
    }
    

提交回复
热议问题