Javascript:为玩家百分比分配随机角色

时间:2020-09-03 05:40:18

标签: javascript arrays random percentage weighted-average

假设我有这两个数组

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

无法全神贯注于如何实现目标。

2 个答案:

答案 0 :(得分:2)

乘以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,并记住始终在使用变量之前声明它们(例如i循环中的for),否则您将隐式创建全局变量,并在严格模式下引发错误。

答案 1 :(得分:0)

为什么不只生成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;
}