Percentage chance of saying something?
I do this all the time with my discord bots
const a = Math.floor(Math.random() * 11);
if (a >= 8) { // 20% chance
/*
CODE HERE
*/
} else { // 80% chance
/*
CODE HERE
*/
}
You can change 11 to 101 if you want.
The reason why it has an extra one is so it does 1 - 10 instead of 1 - 9 (or 1 - 100 instead of 1 - 99)
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");
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.
var arrayShuffle = function(array) {
for ( var i = 0, length = array.length, swap = 0, temp = ''; i < length; i++ ) {
swap = Math.floor(Math.random() * (i + 1));
temp = array[swap];
array[swap] = array[i];
array[i] = temp;
}
return array;
};
var percentageChance = function(values, chances) {
for ( var i = 0, pool = []; i < chances.length; i++ ) {
for ( var i2 = 0; i2 < chances[i]; i2++ ) {
pool.push(i);
}
}
return values[arrayShuffle(pool)['0']];
};
for ( var i = 0; i < 20; i++ ) {
console.log(percentageChance(['hi', 'test', 'bye'], [80, 15, 5]));
}
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.