gpt4 book ai didi

javascript - 加权随机数选择

转载 作者:行者123 更新时间:2023-11-28 15:24:14 27 4
gpt4 key购买 nike

我正在开发一个 node.js 应用程序,必须根据 [0, 100] % 范围内的获胜概率随机选择获胜者

我的代码如下:

var activeGame = {
id: 12324,
type: 1,
active: true,
players: [{
id: 5032,
name: "Username",
foo: true,
winProbability: 56.32 //%
}, {
id: 98243,
name: "Username",
foo: true,
winProbability: 22.68 //%
}, {
id: 10943,
name: "Username",
foo: false,
winProbability: 21.00 //%
}],
};

我发现其他算法不是很清楚,并且不适用于 100% 的概率。

我正在寻找一种方法来创建函数 selectRandomWinner()返回获胜玩家的索引,但我陷入困境,所有帮助都将不胜感激。谢谢!

最佳答案

计算一个从 0 到 100 的随机数。然后循环遍历玩家,将他们的概率添加到总数中,直到总数高于随机数:

var activeGame = {
id: 12324,
type: 1,
active: true,
players: [{
id: 5032,
name: "Joe",
foo: true,
winProbability: 56.32 //%
}, {
id: 98243,
name: "Jane",
foo: true,
winProbability: 22.68 //%
}, {
id: 10943,
name: "Fred",
foo: false,
winProbability: 21.00 //%
}],
};

function pickPlayer() {
var randPct = Math.random() * 100;
var total = 0;
var players = activeGame.players;
var selectedPlayer;
for (var i = 0; i < players.length; i++) {
total += players[i].winProbability;
if (randPct < total) {
selectedPlayer = players[i];
break;
}
}
return selectedPlayer;
}

var results = document.getElementById("results");
var resultObj = {};
for (var i = 0; i < 1000; i++) {
var playerName = pickPlayer().name;
if (resultObj[playerName]) {
resultObj[playerName] ++;
} else {
resultObj[playerName] = 1;
}
}
for (name in resultObj) {
results.innerHTML += "<tr><td>" + name + "</td><td>" + resultObj[name] + "</td></tr>";
}
Results of picking 1000 players:
<table id="results">
<tr>
<th>Name</th>
<th>Count</th>
</table>

关于javascript - 加权随机数选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836122/

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