基于百分比的价值概率

4

有没有一种方法可以根据百分比提取值?

数值概率:
差:1%
普通:29%
好:70%

var move ["bad","normal","good"];

一个简单的条件语句:
if (move == "bad") {
bad_move = "That's a bad move!";
} else if (move == "normal") {
normal_move = "Classic move!";
} else {
good_move = "Amazing move!";
}

那么,对于这种问题,PHP比Javascript更好吗?

其余缺失的概率是什么? - Nina Scholz
"对于这种问题,PHP比JavaScript更好吗?" - 如果有人禁用JS,则JS解决方案不好。答:使用两种方法;服务器端在任何情况下都不会让您失望。 - Funk Forty Niner
@Mlabuit 我明白了。 - Funk Forty Niner
除了这个问题,你意识到你的 JavaScript 中有语法错误了吗? - Daan
我喜欢简单地创建一个包含100个样本的数组,其中70/100是“好”的,1个是“坏”的等等。然后,您可以使用Array.random类型脚本快速获取这些值,而不需要进行多次调用操作。 - dandavis
显示剩余2条评论
2个回答

1
你可以编写一个函数,根据给定的概率百分比来采样值:

function weightedSample(pairs) {
  const n = Math.random() * 100;
  const match = pairs.find(({value, probability}) => n <= probability);
  return match ? match.value : last(pairs).value;
}

function last(array) {
  return array[array.length - 1];
}

const result = weightedSample([
  {value: 'Bad', probability: 1},
  {value: 'Normal', probability: 29},
  {value: 'Good', probability: 70}
]);

console.log(result);

我无法确定PHP是否更好。在PHP中,这种问题应该不会更难或更容易。你应该根据函数应该在服务器端还是客户端运行来决定使用哪个(JS或PHP)。

0

我建议使用概率的连续检查和随机数的余数。

此函数首先将返回值设置为最后一个可能的索引,然后迭代,直到随机值的余数小于实际概率。

这些概率必须总和为一。

function getRandomIndexByProbability(probabilities) {
    var r = Math.random(),
        index = probabilities.length - 1;

    probabilities.some(function (probability, i) {
        if (r < probability) {
            index = i;
            return true;
        }
        r -= probability;
    });
    return index;
}

var i,
    move = ["bad", "normal", "good"],
    probabilities = [0.01, 0.29, 0.7],
    count = {},
    index;

move.forEach(function (a) { count[a] = 0; });

for (i = 0; i < 1e6; i++) {
    index = getRandomIndexByProbability(probabilities);
    count[move[index]]++;
}

console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接