bockzior
bockzior

Reputation: 536

Weighted Random number selection

I'm developing a node.js app where a winner has to be randomly selected based on it's win probability in the range of [0, 100] %

My code is as follows:

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 //%
    }],
};

I've found other algorithms that weren't very clear and didn't work with probabilities adding up to 100%.

I'm looking for a way to create a function selectRandomWinner() to return the index of the winning player but I'm stuck and all and any help would be greatly appreciated. Thanks!

Upvotes: 1

Views: 250

Answers (1)

Barmar
Barmar

Reputation: 782785

Calculate a random number from 0 to 100. Then loop through the players adding their probability to a total, until the total is higher than the random number:

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>

Upvotes: 4

Related Questions