Percentage chance of saying something?

匆匆过客 提交于 2019-12-03 01:38:08

问题


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

回答1:


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.




回答2:


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



回答3:


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



回答4:


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]


来源:https://stackoverflow.com/questions/11552158/percentage-chance-of-saying-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!