Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percentage chance of saying something?

I want to write a program that:

  • 80% of the time will say sendMessage("hi");
  • 5% of the time will say sendMessage("bye");
  • and 15% of the time will say 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"); } 
like image 654
0x29A Avatar asked Jul 19 '12 00:07

0x29A


People also ask

How do you find the probability with percentages?

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%.

How do you do a random chance in Java?

The solution is simple: double r = random.


2 Answers

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.

like image 119
Ernest Friedman-Hill Avatar answered Sep 22 '22 06:09

Ernest Friedman-Hill


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"); 
like image 44
sarnold Avatar answered Sep 23 '22 06:09

sarnold