I want to write a program that:
sendMessage("hi");
sendMessage("bye");
sendMessage("Test");
Does it have to do something with Math.random()
? like
if (Math.random() * 100 < 80) { sendMessage("hi"); } else if (Math.random() * 100 < 5) { sendMessage("bye"); }
How do I convert odds to percentage? Convert the odds to a decimal number, then multiply by 100. For example, if the odds are 1 in 9, that's 1/9 = 0.1111 in decimal form. Then multiply by 100 to get 11.11%.
The solution is simple: double r = random.
Yes, Math.random()
is an excellent way to accomplish this. What you want to do is compute a single random number, and then make decisions based on that:
var d = Math.random(); if (d < 0.5) // 50% chance of being here else if (d < 0.7) // 20% chance of being here else // 30% chance of being here
That way you don't miss any possibilities.
For cases like this it is usually best to generate one random number and select the case based on that single number, like so:
int foo = Math.random() * 100; if (foo < 80) // 0-79 sendMessage("hi"); else if (foo < 85) // 80-84 sendMessage("bye"); else // 85-99 sendMessage("test");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With