首页 > 解决方案 > Javascript:为玩家分配随机角色的百分比

问题描述

假设我有这两个数组

let players = ["ryan", "austin", "julian", "kelso", "mitch", "adam", "dwight", "edwin", "connor", "george"]
let roles = []

我想以随机顺序填充角色,假设 30% 的“好”和 70% 的“坏”字符串,但总是 30% 的“好”角色。

example: roles: ['Bad','Bad','Bad','Bad','Good','Bad','Bad','Bad','Good','Good']

我目前正在运行这个场景,它随机创建一个数组,但没有“好”与“坏”的百分比要求。

players: [ ]
roles: []

while (good === false || bad === false) {
    roles = []
    for (i = 0; i < players.length; i++) {
        let randomise = Math.floor(Math.random() * 2)
        if (randomise === 0) {
            roles.push("Good")
            innocent = true
        } else {
            roles.push("Bad")
            traitor = true
        }
    };
}

无法理解如何实现我的目标。

标签: javascriptarraysrandompercentageweighted-average

解决方案


通过乘以3 / 10 ceil'd 确定有多少玩家必须是优秀的。在循环中,将随机的好或坏值推送到数组中。但是,还要检查您是否已达到要推送的好值或坏值的限制,在这种情况下推送另一个值

const players = ["ryan", "austin", "julian", "kelso", "mitch", "adam", "dwight", "edwin", "connor", "george"]
let goodCount = Math.ceil(players.length * 3 / 10);
console.log('Need total of', goodCount, 'good');
const roles = []
for (let i = 0; i < players.length; i++) {
  if (goodCount === 0) {
    // Rest of the array needs to be filled with bad:
    roles.push('Bad'); continue;
  }
  if (goodCount === players.length - roles.length) {
    // Rest of the array needs to be filled with good:
    roles.push('Good'); goodCount--; continue;
  }
  if (Math.random() < 0.3) {
    roles.push('Good'); goodCount--;
  } else {
    roles.push('Bad');
  }
};
console.log(roles);

记住在可能的情况下使用const而不是let,并且记住在使用它们之前总是声明你的变量(例如循环i中的for),否则你将隐式创建全局变量,并在严格模式下抛出错误。


推荐阅读