简体   繁体   中英

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!

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM