Percentage chance of saying something?

前端 未结 5 1128
自闭症患者
自闭症患者 2021-01-30 05:09

How do I make it so ..

  • 80% of the time it will say sendMessage(\"hi\");
  • 5 % of the time it will say sendMessage(\"bye\");
  • <
5条回答
  •  粉色の甜心
    2021-01-30 05:39

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

提交回复
热议问题