某件事发生的概率,使用整数作为百分比



我正在做一个工作系统,你可以在一个不和谐的机器人中挖掘不同类型的矿石。根据您的技能,接收某些矿石的机会(存储在数据库中)会发生变化。有些会有0%的机会在某些技能水平。在技能1中,机会如下:

let coal_chance = 80
let copper_chance = 15
let iron_chance = 5
let gold_chance = 0
let diamond_chance = 0
let emerald_chance = 0

和技能2:

let coal_chance = 50
let copper_chance = 35
let iron_chance = 10
let gold_chance = 5
let diamond_chance = 0
let emerald_chance = 0

以此类推。我的问题是,我该如何基于这些百分比创造一个机会系统?

我尝试使用Math.Random()和if语句制作系统,但由于我必须每次检查不同数量的值,我必须为每个技能级别制作一个值,如果我想在数据库中将某个ore的机会设置为0%,我还必须更改代码。

我根据@sudheeshix的评论想出了一个粗略的解决方案:

const cumulativeChances = [ 
{c: 100, i: "coal"},
{c: 50, i: "copper"},
{c: 15, i: "iron"},
{c: 5, i: "gold"},
{c: 0, i: "emerald"},
{c: 0, i: "diamond"}
]
const mineOre = () => {
let rng = Math.random() * 100
let won = 'coal'
for (item of cumulativeChances) {
if (item.c < rng) break
won = item.i
}
return won
}
// Testing if it works as intended
const calculatedChances = {
coal: 0,
copper: 0,
iron: 0,
gold: 0,
emerald: 0,
diamond: 0
}
let tries = i = 10000;
while(i--) {
let won = mineOre()
calculatedChances[won] += (1 / tries * 100)
}
console.log(calculatedChances)

可能还有改进的空间,但它提供了一个想法。快乐编码:)

有一种方法:

将资源值转换为数组:

resources = ["coal", "copper", "iron", "gold", "diamond", "emerald"];
chances = [80, 15, 5, 0, 0, 0];

然后,根据这个答案生成百分比的累积和。

const cumulativeSum = (sum => value => sum += value/100)(0);
cum_chances = chances.map(cumulativeSum);

这些值除以100得到浮点值,因为这就是Math.random()生成的:0到1之间的值。有了上面提到的chances的值,这将使cum_chances具有[0.8, 0.95, 1, 1, 1, 1]的值。

现在,生成随机概率。

random_prob = Math.random();

并根据这个答案找到random_prob所在的第一个数组项的索引。

idx = cum_chances.findIndex(function (el) {
return el >= random_prob;
});
resource_found = resources[idx];

例如,如果random_prob是0.93,这将给你一个索引1,因此,resources[idx]将给你"copper"

最新更新