algorithm - 如何按一定比例随机选择

标签 algorithm random probability

我想在两个概率不等的备选方案之间随机*选择。

例如,当用户按下一个按钮时,25% 的时间会发出声音 A,75% 的时间会发出声音 B。我可以手动设置简单的比例,例如 1:4 和 2:4,但我我在处理 3:5 这样的比例时遇到了麻烦。

一般的思考方式是什么?

*I mean unpredictable when looked at one-by-one. I notice any question with the word random in it gets a Mensa of pedants.

最佳答案

比率 3:5 相当于 37.5% 的时间或 0.375(3 倍是 A,5 倍是 B,所以 3/8 是 37.5%)。所以你可以这样计算:

random() < 0.375 ? "A" : "B"

来自

http://en.wikipedia.org/wiki/Ratio

If there are 2 oranges and 3 apples, the ratio of oranges to apples is shown as 2:3, whereas the fraction of oranges to total fruit is 2/5.

关于algorithm - 如何按一定比例随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4331448/

相关文章:

java - 图像层和形状之间的碰撞检测

java - 如何使用 math.random 重新随机化网格上的绘图

statistics - 如何从多项分布中采样?

statistics - 找到具有相同负载的 TCP 数据包的概率?

盈亏博弈中最优预期金额的算法

java - 如何找到两个多行字符串之间的相似度百分比?

algorithm - 图的平均最短路径长度和直径算法的时间复杂度是否存在差异?

algorithm - 如何在 Java 中将纬度和经度转换为 x,y?

matlab - 将 3d 坐标存储在点列表中 Matlab

java - 在 Java 中使用 3 维数组的卡片组