我该怎么做..
sendMessage("hi");
sendMessage("bye");
sendMessage("Test");
是否必须对Math.random()执行某些操作? 喜欢
if (Math.random() * 100 < 80) {
sendMessage("hi");
}
else if (Math.random() * 100 < 5) {
sendMessage("bye");
}
答案 0 :(得分:45)
是的,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
这样你就不会错过任何可能性。
答案 1 :(得分:16)
对于这样的情况,通常最好生成一个随机数并根据该单个数字选择案例,如下所示:
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");
答案 2 :(得分:1)
我一直用我的不和谐机器人这样做
const a = Math.floor(Math.random() * 11);
if (a >= 8) { // 20% chance
/*
CODE HERE
*/
} else { // 80% chance
/*
CODE HERE
*/
}
如果需要,您可以将 11 更改为 101。
为什么它有一个额外的原因是它做 1 - 10 而不是 1 - 9(或 1 - 100 而不是 1 - 99)
答案 3 :(得分:0)
我通过创建一个池并使用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]));
}
答案 4 :(得分:0)
产生20%的机会获得“ Yupiii!”在cancel.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()
答案 5 :(得分:-1)
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;
}