我如何生成 A = 1 和 B = 10 之间的随机数,其中每个数字都有不同的概率?
例子:数字/概率
1 - 20%
2 - 20%
3 - 10%
4 - 5%
5 - 5%
...等等。
我知道一些硬编码的变通办法,不幸的是,这些变通办法对更大的范围没有用,例如 A = 1000 和 B = 100000。
假设我们有一个
Rand()
返回随机数 R 的方法,0 < R < 1,任何人都可以发布代码示例并以正确的方式执行此操作吗?可在 c#/java/actionscript 中使用。
最佳答案
构建一个包含 100 个整数的数组,并用 20 个 1、20 个 2、10 个 3、5 个 4、5 个 5 等填充它。然后从数组中随机选择一个项目。
int[] numbers = new int[100];
// populate the first 20 with the value '1'
for (int i = 0; i < 20; ++i)
{
numbers[i] = 1;
}
// populate the rest of the array as desired.
// To get an item:
// Since your Rand() function returns 0 < R < 1
int ix = (int)(Rand() * 100);
int num = numbers[ix];
如果项目的数量相当少并且您的精度不太严格,则此方法效果很好。也就是说,如果您想要 4.375% 的 7,那么您需要一个更大的数组。
关于algorithm - 在不同概率范围内生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635448/