首页 > 解决方案 > 使用概率选择数组值

问题描述

我有一个作业要做,那就是:

给定以下概率,从黄色、蓝色和红色中选择一种随机颜色: 黄色:3/7 蓝色:1/7 红色:3/7


我知道我可以通过使用类似的东西来解决这个问题:[yellow, yellow, yellow, blue, red, red, red] 但我不认为这在编程上是好的,因为当我有机会时,我会有更改数组。

所以,我想我可以尝试一些类似重量的方法

let yellow_probability = 3/7
let blue_probability = 1/7
let red_probability = 3/7

const colors = ['yellow', 'blue', 'red']

function pickPosition(yellow_probability, blue_probability, red_probability){

    let yellow_weight = Math.random() * yellow_probability
    let blue_weight = Math.random() * blue_probability
    let red_weight = Math.random() * red_probability

    let weights = [yellow_weight, blue_weight, red_weight]

    let max_of_array = Math.max.apply(Math, weights);

    pickedColor = weights.indexOf(max_of_array)

    return pickedColor

}
pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
pickedColor = colors[pickedColorIndex]
console.log(pickedColor)

我做了一个测试:

let n=1000000; 
let yellow=0, blue=0, red=0; 
for (let i=0; i<n; i++) {

    pickedColorIndex = pickPosition(yellow_probability, blue_probability, red_probability)
    if (pickedColorIndex==0) yellow++
    else if (pickedColorIndex==1) blue++
    else red++;
}
console.log("yellow = " + yellow/n );
console.log("blue = " + blue/n );
console.log("red = " + red/n );

我希望这个测试能输出如下内容:

Yellow = 0.43
Blue = 0.14
Red = 0.43

但我得到:

Yellow = 0.48
Blue = 0.03
Red = 0.48

有趣的是,代码在概率相等 (1/3, 1/3, 1/3) 或类似 (1/2, 1/2, 0) 时有效

谁能指出我做错了什么?

标签: javascriptarraysrandom

解决方案


您可以创建尽可能多的不同项目,而不是单个随机值,然后再获取具有最大值的项目。

这促进了具有更高因素/概率的值/项目。

代替这种方法,您可以采用单个随机值并将所有概率放入一个数组中,然后检查随机值的区间。拿这个项目。


编辑:代码

function getRandomIndex(probabilities) {
    var random = Math.random(),
        i;
        
    for (i = 0; i < probabilities.length; i++) {
        if (random < probabilities[i]) return i;
        random -= probabilities[i];
    }
    return probabilites.length - 1;
}

var probabilities = [3 / 7, 1 / 7, 3 / 7],
    j = 1e6,
    count = [0, 0, 0];

while (j--) count[getRandomIndex(probabilities)]++;

console.log(count);


推荐阅读