假设我有一个数组
var list = ['a', 'b', 'c', 'd'];
Run Code Online (Sandbox Code Playgroud)
我想从List随机中选择一个值.如果它是完全随机的,每个人有25%的几率.有没有办法随机选择一个像这样的偏差值:
var bias = [0.1, 0.2, 0.1, 0.6];
Run Code Online (Sandbox Code Playgroud)
(偏差当然加起来1)
所以'a'有10%的几率被选中,'b'有20%被选中的机会等等
编辑:我知道我可以修改do var list = ['a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd', 'd']并只是随机选择一个值,但我正在寻找一种更有效的方法,只需要一个包含偏差的数组.
制作累积偏见列表:
var sum = 0;
var cumulativeBias = bias.map(function(x) { sum += x; return sum; });
Run Code Online (Sandbox Code Playgroud)
然后,从做一个随机数0的sum(即cumulativeBias[cumulativeBias.length - 1]):
var choice = Math.random() * sum;
Run Code Online (Sandbox Code Playgroud)
然后搜索第一个元素,cumulativeBias大于choice.您可以使用二进制搜索来获得速度,但对于简短列表,顺序搜索就足够了.该元素的索引是所选索引.例如,类似于:
var chosenIndex = null;
cumulativeBias.some(function(el, i) {
return el > choice ? ((chosenIndex = i), true) : false;
});
chosenElement = list[chosenIndex];
Run Code Online (Sandbox Code Playgroud)
我过去曾用以下方式写过这篇文章:
用运行总数替换您的偏差 - 即将bias[0]添加到bias[1],然后将bias[1]添加到bias[2],然后将bias[2]添加到bias[3]。
在你上面的例子中,你会得到var bias = [0.1, 0.3, 0.4, 1.0]- 最后一个应该总是 1,否则你做错了什么。
现在选择一个 0 到 1.0 之间的随机数;找到偏差数组中的最大数,即小于您的随机数。从列表数组中选择相应的值。
编辑:@Amadan 是对的。我的意思是,找到偏差数组中的最小数字,即大于您的随机数。我的“最小”和“最大”是错误的:)