Percentage chance of saying something?

前端 未结 5 1129
自闭症患者
自闭症患者 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 06:00

    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.

提交回复
热议问题