0x29A - 12 days ago 5x

Java Question

How do I make it so ..

- 80% of the time it will say
`sendMessage("hi");`

- 5 % of the time it will say
`sendMessage("bye");`

- and 15% of the time it 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");

}

Answer

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:

```
double 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.

Source (Stackoverflow)

Comments