Percentage chance of saying something?

Viewed 85165

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");
}
7 Answers

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]));
}

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)

Generate a 20% chance to get "Yupiii!" in the console.log

const testMyChance = () => {

  const chance = [1, 0, 0, 0, 0].sort(() => Math.random() - 0.5)[0]

  if(chance) console.log("Yupiii!")
  else console.log("Oh my Duck!")
}

testMyChance()

Java

/**
 * Zero or less returns 'false', 100 or greater returns 'true'. Else return probability with required percentage.
 * @param percentage for example 100%, 50%, 0%.
 * @return true or false with required probability.
 */
private static boolean probably(int percentage) {
    double zeroToOne = Math.random(); // greater than or equal to 0.0 and less than 1.0
    double multiple = zeroToOne * 100; // greater than or equal to 0.0 and less than 100.0
    return multiple < percentage;
}

JavaScript

function probably(percentage) {
  return Math.random() * 100 < percentage;
}

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

var a = [true, false, false]
a.sort(function(){ return Math.random() >= 0.5 ? 1 : -1 })[0]
Related