Javascript:分配一定比例的玩家随机角色

Javascript: Assign percentage of players a random role

假设我有这两个数组

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

我想填充 roles,假设 30% 的 'Good' 和 70% 'Bad' 字符串随机排列,但总是 30 'Good' 个角色的百分比。

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

我目前 运行 这个场景随机创建一个数组,但没有 'Good' 与 'Bad' 的百分比要求。

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
        }
    };
}

我不知道如何实现我的目标。

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

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);

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

你为什么不只生成一个 70% 的“坏”和 30% 的“好”的数组,然后打乱这个数组:

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

const badNum = Math.floor(0.7 * players.length);
const goodNum = players.length - badNum;

for (let i = 1; i <= players.length; i++) {
    roles.push(i <= badNum ? "bad" : "good");
}

//Shuffle roles
for (let i = 0; i < roles.length; i++) {
    var randomIndex = Math.floor(Math.random() * (roles.length - i)) + i;
    var selection = roles[randomIndex];
    var extract = roles[i];
    roles[i] = selection;
    roles[randomIndex] = extract;
}