How to choose randomly in a certain ratio

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

For example, when the user presses the button, in 25% of cases he will make sound A and 75% of the time, sound B. I can manually make simple ratios, such as 1: 4 and 2: 4, but I'm having problems with coefficients, such as 3: 5.

What is the general way to think about this?

* I mean unpredictable when I looked one after another. I notice any question with the word random in it gets Mensa of pedants.

+3
source share
5 answers

3: 5 , 8, 8. 0, 1 2 ( ), A, 3, 4, 5, 6 7 ( ), B. , , 3.

- 3: 5: 4 12 (3 + 5 + 4), 3, A, 8 (3 + 5) B, C.

, , , O (n). SO, , ( ) .

+4

3: 5 37,5% 0,375 ( 3 A, 5 B, 3/8 37,5%). :

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

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

2 3 , 2: 3, 2/5.

+5

0 1, :

, x. (, 3: 2 3/5 0,6) y [0,1]. y < x , .

+3

Assuming your random number generator returns a double value between 0.0 and 1.0, you are simply comparing the exact ratio you want. In case of 3 out of 5, you should check if the random value was less than 0.6.

if(rand < 0.6) {
    playSound(A);
}
else {
    playSound(B);
}
+1
source
if (random() % (A+B) < A) 
   do_A() 
else
   do_B();
+1
source

Source: https://habr.com/ru/post/1778027/


All Articles