javascript - 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
}
};
}
无法理解如何实现我的目标。
解决方案
通过乘以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
),否则你将隐式创建全局变量,并在严格模式下抛出错误。
推荐阅读
- c# - 嵌套的 Gridview 在每一行 DataBound 上显示相同的数据并在子 Gridview 中下载文件
- .net-core - 如何在 .NET Core 项目中使用 WSDL Web 服务?
- schema - 带有空格字符的 Avro 枚举符号
- facebook - 从您的个人资料中删除您自己的应用程序的权限
- regex - 使用正则表达式排除 URL 中的文件夹
- python - 使用 Python 列表和数组
- powershell - 访问与服务帐户共享的 Google 表格文件会产生 403 禁止错误
- android - Realm Android:在数据模型类中添加领域对象作为子数组
- android - AIR / Android:在清单中添加资产和引用
- webpack - 如何删除 webpack 插件中的条目?