生成总和为常数的随机数 [英] generate random numbers of which the sum is constant
问题描述
我在想是否有办法生成一组总和始终为常数的随机数.例如,20 可以分为 5 个数字(1、2、3、4、10)我不在乎这 5 个数字中的每一个是什么,只要它们的总和等于 20.无论如何以编程方式这样做?
I am thinking if there is anyway to generate a set of random numbers of which the sum is always a constant. For example, 20 can be divided into 5 numbers ( 1, 2,3,4,10) I don't care what each of the 5 numbers is as long as their sum is equal to 20. Is there anyway to do so programmatically?
推荐答案
要获得均匀分布,诀窍是将总和视为数轴,而不是为段生成随机数,而是生成 n-1数字作为沿线的点,然后减去以获得线段.这是 ojrandlib 中的函数:
To get a uniform distribution, the trick is to think of your sum as a number line, and rather than generating random numbers for the segments, generate n-1 numbers as points along the line, and subtract to get the segments. Here's the function from ojrandlib:
static int compare(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
void ojr_array_with_sum(ojr_generator *g, int *a, int count, int sum) {
int i;
for (i = 0; i < count-1; ++i) { a[i] = ojr_rand(g, sum+1); }
qsort(a, count-1, sizeof(int), compare);
a[count-1] = sum;
for (i = count-1; i > 0; --i) { a[i] -= a[i-1]; }
}
ojr_rand(g, limit)
生成一个从 0 到 limit-1 的统一随机整数.这个函数然后用 count
个随机整数填充数组 a
,这些整数与 sum
相加.将此适应任何其他 RNG 应该不会太难.
ojr_rand(g, limit)
generates a uniform random integer from 0 to limit-1. This function then fills the array a
with count
random integers that add to sum
. Shouldn't be too hard to adapt this to any other RNG.
这篇关于生成总和为常数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!