加权随机数选择

时间:2015-04-23 23:28:23

标签: javascript random

我正在开发一个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%的概率。

我'正在寻找一种方式来创建一个function selectRandomWinner()返回获胜玩家的索引,但我' M卡和所有和任何帮助将不胜赞赏。谢谢!

1 个答案:

答案 0 :(得分:4)

计算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>";
}
&#13;
Results of picking 1000 players:
<table id="results">
  <tr>
    <th>Name</th>
    <th>Count</th>
</table>
&#13;
&#13;
&#13;