Array of random numbers with a sum in a given range?

In C, how do I get an array of n numbers (each 0x00-0xFF in my case), of which the sum is in the given range 0..k ?

Almost duplicated C ++ plural random numbers, summing up to equal a certain number , specify a certain amount, but in my case, the sum can be something between 0..k .

+7
c algorithm random
source share
3 answers

You need to indicate what the desired distribution of random numbers is.

If there are no additional requirements, I would suggest one of the following:


(one)

  • select a random number a [1] in the interval 0 .. k
  • select a random number a [2] in the interval 0 .. ka [1]
  • select a random number a [3] in the interval 0 .. ka [1] -a [2]
  • ...
  • select a random number a [n] in the interval 0 .. ka [1] -a [2] -...- a [n-1]

If you have an upper limit m in a random number range, use min (ka [1] -... m) as the upper limit of the interval.

Disadvantages: you will get many small rooms and several large ones.


(2)

  • select n random numbers a [1], ..., a [n] in the interval 0 .. m, m is the upper limit
  • s = a [1] + a [2] + ... + a [n]
  • multiply each a [i] by k / s (if integers are required, round down)

Disadvantages: It is unlikely that these numbers will become large. If integers are required, there will likely be a gap between the sum of the numbers and k due to a rounding error.


I think you get "more pleasant" rooms with option (2), but as stated above, it depends on the requirements.

+4
source share

Assuming k less than 255 * n , one solution should assign k / n each element of the array, and then randomly subtract the value for the elements of the array.

 // for (int i = 0; i < n; i++) array[i] = k / n; // for (int i = 0; i < n; i++) array[i] -= randbetween(0, array[i]); for (int i = 0; i < n; i++) array[i] = randbetween(0, k / n); 

This is the expected amount of k / 2 . By setting the randbetween() function, you can change the probability of the resulting sum of the array.

+3
source share

It is easy to create a single number within the range [0, 255] .

It is easy to identify if k > 255*n or k < 0 there is no solution.

If 0 <= k <= 255*n , a solution exists. Here we are only talking about the state n > 1 .

You created n-1 random numbers, and the sum of the numbers n-1 is s1 , suppose the nth number is x . So, s1 + x = k , and x should be [0, 255] . If the numbers n-1 are within the range [0, a] , then (n-1)*a + 255 >= k , we get a >= (k-255)/(n-1) .

If k > 255 , just let a = (k-255)/(n-1) . This means that s1 is [0, k-255] . Then the nth number x can be any random number inside [0, 255] . Thus, the solution arbitrarily selects n-1 numbers within [0, (k-255)/(n-1)] (you know (k-255)/(n-1) <= 255 , so it satisfies your condition) and choose one random number within [0, 255] .

If k <= 255 , an arbitrary choice of n numbers within [0, k/n] (you know that k/n is within [0, 255]).

+1
source share

All Articles