选择百分比随机获胜者

时间:2017-01-05 18:42:29

标签: javascript

我想从大约2到10名玩家中选择一名随机赢家。 每个球员都有获胜的机会。有人有50%,有人有10%。

假设我们有2名球员。一名球员有20%,另一名有80%。如何在这两者之间选择获胜者?

玩家在阵列中

var players = {
    player1: {
        chance: 20 //%
    }
    player2: {
        chance: 80 //%
    }
}

//Select winner from json

2 个答案:

答案 0 :(得分:1)

(假设所有百分比都加起来为100)

首先你必须订购球员。然后从1到100取一个随机数,找出随机数属于哪个玩家。

例如:

// Modified json to array so we can easily loop through them
// If you would like help turning the json to an array, I can provide code for that upon request
var players = [
    {
        chance: 20
    },
    {
        chance: 40
    },
    {
        chance: 40
    }
];

// Generate random number
var perc = Math.random() * 100; // between 0 and 99.999~
// Save where we are in the percentage
var currentPerc = 0;

// Loop through the players and check who the random number chose
for ( var pID = 0; pID < players.length; pID++ ) {

    // Check if the current player we are looking at has won
    if (perc < (players[pID].chance + currentPerc)) {
        alert("PLAYER " + (pID + 1) + " HAS WON.");
        // Do player winning code here
        break; // break out of the loop, we're done
    } else {
        currentPerc += players[pID].chance;
    }
}

在上面的例子中,假设随机数选择了45(0.45 * 100,因为math.random给我们0.0到0.99~)。 这意味着玩家2赢了

 0 to  20 = Player 1 wins
21 to  60 = Player 2 wins
61 to 100 = Player 3 wins

使用45作为随机数选择第一次迭代,我们检查玩家1是否赢了。他没有,所以我们将玩家1的百分比添加到&#34;当前百分比&#34;。

然后在第二次迭代中我们检查玩家2.因为45&lt; (20 + 40),选手2获胜。我们警告他已赢了,并会为此做一些代码。

答案 1 :(得分:0)

var players = [20,5,15,40,20];
var getWinner = function(players){
  var random = Math.random();
  var sum = 0;
  for(var i = 0; i < players.length; i++){
    sum+= players[i]/100;
    if(random<= sum) return i;
  }
}

返回获胜的玩家(索引0)的编号