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");
}
For cases like this it is usually best to generate one random number and select the case based on that single number, like so:
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:That way you don't miss any possibilities.
Here is a very simple approximate solution to the problem. Sort an array of true/false values randomly and then pick the first item.
This should give a 1 in 3 chance of being true..
I made a percentage chance function by creating a pool and using the fisher yates shuffle algorithm for a completely random chance. The snippet below tests the chance randomness 20 times.