【问题标题】:Javascript: Assign percentage of players a random roleJavascript:为玩家分配随机角色的百分比
【发布时间】:2020-12-22 07:55:09
【问题描述】:

假设我有这两个数组

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

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

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

无法思考如何实现目标。

【问题讨论】:

    标签: javascript arrays random percentage weighted-average


    【解决方案1】:

    乘以3 / 10ceil'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);

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

    【讨论】:

    • 这不会始终导致 30% 的好角色。
    • 您说您希望角色是随机的。随机性不能保证产生平均比率。
    • 我想我应该更好地澄清一下。我需要 30% 才能始终保持良好状态,但顺序随机。我将修改我的问题以包含它。
    • 好的,看编辑,先弄清楚你需要多少商品,然后在每次迭代中减去
    • 这很漂亮。也感谢您离开 cmets,这样更容易理解和学习!
    【解决方案2】:

    为什么不直接生成一个包含 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      相关资源
      最近更新 更多