从列表中随机选择项目,每个都有不同的机会 [英] pick item from list at random, each has different chance
问题描述
我想编写一个简单的函数,该函数允许从列表中滚动随机项目,我使用以下代码来做到这一点:
I wanted to write a simple function that allows to roll random item from list, i did it with this code:
this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];
this.assign_resource = function() {
var index = tools.rnd(0, this.resources.length - 1);
return this.resources[index];
};
但是它不能很好地发挥作用,所以我想将其更改为不同的系统,该系统允许列出项目(包括空的项目),并且它随机选择一个项目,但是每个项目都有不同的机会(例如,这个项目有10个机会%,这是20%).也许有人可以帮助我实现这种功能.
But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.
已编辑-----
例如,这可能是新列表:
for example this could be new list:
this.resources = [
{ type: 'empty', chance: 30 },
{ type: 'nitrogen', chance: 10 },
{ type: 'silicon', chance: 20 },
{ type: 'cobalt', chance: 30 },
{ type: 'magnesium', chance: 10 }
];
现在如何使用它以使其正确发生?
How to use it now to make it happen properly?
已编辑2 -----
我试图找出使用数学完成的编程解决方案,而不是简单地复制数组中的项,答案在
I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.
推荐答案
我将其设置为只有实际资源在您的数组中,如果随机滚动不在这些范围内,则会发生空".
I would set it up so that only the actual resources are in your array and "empty" happens if the random roll falls outside of those.
this.resources = [
{ type: 'nitrogen', chance: 10 },
{ type: 'silicon', chance: 20 },
{ type: 'cobalt', chance: 30 },
{ type: 'magnesium', chance: 10 }
];
this.assign_resource = function() {
var rnd = Math.random();
var acc = 0;
for (var i=0, r; r = this.resources[i]; i++) {
acc += r.chance / 100;
if (rnd < acc) return r.type;
}
// rnd wasn't less than acc, so no resource was found
return 'empty';
}
这篇关于从列表中随机选择项目,每个都有不同的机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!