Javascript 说出某事的机会百分比?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11552158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Percentage chance of saying something?
提问by 0x29A
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");
- 80%的时候它会说
sendMessage("hi");
- 5% 的时候它会说
sendMessage("bye");
- 15% 的时候它会说
sendMessage("Test");
Does it have to do something with Math.random()? like
它是否与 Math.random() 有关系?喜欢
if (Math.random() * 100 < 80) {
sendMessage("hi");
}
else if (Math.random() * 100 < 5) {
sendMessage("bye");
}
回答by Ernest Friedman-Hill
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:
是的,这Math.random()
是实现这一目标的绝佳方式。你想要做的是计算一个随机数,然后根据它做出决定:
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.
这样你就不会错过任何可能性。
回答by sarnold
For cases like this it is usually best to generate onerandom 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");
回答by Jake
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.
我通过创建一个池并使用 Fisher yates shuffle 算法来获得一个完全随机的机会,从而创建了一个百分比机会函数。下面的代码片段测试了机会随机性 20 次。
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]));
}
回答by seanbehan
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]