gpt4 book ai didi

javascript - 从数组中选择随机元素时如何获得平衡输出?

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:46 24 4
gpt4 key购买 nike

作为一个有趣的项目,我正在开发一款板球模拟器游戏,其中一个主要方面是在每次投球时获得随机结果。

一般来说,在Test Cricket中,有以下几种可能:

"0", "1" happen very frequently (60% of the time)

"2", "3" happen moderately (25% of the the time)

"FOUR", "SIX", "OUT" happen rarely (10% of the time)

"WIDE BALL", "NO BALL" happen very rarely (2% of the time)

如果我有一个数组,例如:

var possible_outcomes = ["0","1","2","3","FOUR","SIX","OUT","WIDE BALL","NO BALL"];

当从 possible_outcomes 中抽取随机项目时,经过固定的迭代次数(比如 60),获得上述概率的最佳方法是什么。

PS:如果你们中的一些人不了解这项运动,我很抱歉。我使用了几个与板球相关的术语,因为我不知道如何更好地解释。

最佳答案

我建议使用连续检查概率和随机数的其余部分。

此函数首先将返回值设置为最后一个可能的索引并迭代,直到其余随机值小于实际概率。

概率之和必须为一。

function getRandomIndexByProbability(probabilities) {
var r = Math.random(),
index = probabilities.length - 1;

probabilities.some(function (probability, i) {
if (r < probability) {
index = i;
return true;
}
r -= probability;
});
return index;
}

var i,
action = ["0", "1", "2", "3", "FOUR", "SIX", "OUT", "WIDE BALL", "NO BALL", "other"],
probabilities = [0.3, 0.3, 1 / 8, 1 / 8, 1 / 30, 1 / 30, 1 / 30, 0.01, 0.01, 0.03],
count = {},
index;

action.forEach(function (a) { count[a] = 0; });

for (i = 0; i < 1e6; i++) {
index = getRandomIndexByProbability(probabilities);
count[action[index]]++;
}

console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 从数组中选择随机元素时如何获得平衡输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41119460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com