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: 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, , ( ) .
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.
0 1, :
, x. (, 3: 2 3/5 0,6) y [0,1]. y < x , .
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); }
if (random() % (A+B) < A) do_A() else do_B();
Source: https://habr.com/ru/post/1778027/More articles:JBoss reloads a trust certificate without rebooting - java-eeRegular expression pattern with sub-table exceptions (Python) - pythonProblem calling a web service from a JBOSS EJB service - javaОтладка: почему раздел, связанный с данными, прерывается при повторном применении DataContext? - data-bindinghow to replace char with char * - cIs it possible to resize / move layouts to android at runtime? - android-layoutNeed help disassembling markdowns, delete italics (*), but not bold (**) - javascriptLua - File Access and Application Management? - luaJava Swing - JPanel and GridLayout Margins / Padding - javamultiple Spring root WebApplicationContexts - javaAll Articles