generate random numbers of which the sum is constant

后端 未结 7 751
暗喜
暗喜 2020-12-03 15:40

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 do

7条回答
  •  春和景丽
    2020-12-03 16:14

    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) 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.

提交回复
热议问题