可以说,我想按百分比机会触发一个函数
function A () { console.log('A triggered'); } //50% chance to trigger
if (Math.random() >= 0.5) A();
现在我想添加更多功能来偶然触发,我所做的是
//method 1
function B () { console.log('B triggered'); } //10% chance to trigger
function C () { console.log('C triggered'); } //10% chance to trigger
if (Math.random() >= 0.5) {
A();
} else if (Math.random() > (0.5 + 0.1)) {
B();
} else if (Math.random() > (0.5 + 0.1 + 0.1)) {
C();
}
但这使得A()
在之前获得优先权B() and C()
。因此我将代码更改为
//method 2
var randNumber = Math.random();
if (randNumber <= 0.5) { A(); }
else if (randNumber > 0.5 && randNumber <= (0.5 + 0.1)) { B(); }
else if (randNumber > (0.5 + 0.1) && randNumber <= (0.5 + 0.1 + 0.1)) { C(); }
这个方法看起来fair但它看起来效率很低,因为它需要在每个单独的机会中进行硬编码if else
函数,如果我有一个很长的列表功能及触发机会,我需要做if else
又长又乱
问题是有什么方法可以更好、更有效地做到这一点吗?与我上面显示的这两种方法不同。
*also 光明正大也很重要(听起来像游戏)
抱歉,如果我解释得不好,我们将不胜感激。谢谢。
您可以创建一个要调用的函数及其被调用机会的列表。然后,您使用机会将随机数的范围划分为多个块。在这个例子中它将是:
0.0 0.5 0.6 0.7
0.5/A 0.1/B 0.1/C
条目不需要根据机会进行排序。如果机会之和大于 1.0,则不会调用数组的最后一个元素。这是您需要通过这种方法来确保自己的事情。
代码可能如下所示:
function A() {
console.log('A was called')
}
function B() {
console.log('B was called')
}
function C() {
console.log('C was called')
}
var list = [
{chance: 0.5, func: A},
{chance: 0.1, func: B},
{chance: 0.1, func: C}
];
function callRandomFunction(list) {
var rand = Math.random() // get a random number between 0 and 1
var accumulatedChance = 0 // used to figure out the current
var found = list.find(function(element) { // iterate through all elements
accumulatedChance += element.chance // accumulate the chances
return accumulatedChance >= rand // tests if the element is in the range and if yes this item is stored in 'found'
})
if( found ) {
console.log('match found for: ' + rand)
found.func()
} else {
console.log('no match found for: ' + rand)
}
}
callRandomFunction(list)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)