Program that gets a user input N
and finds 5 random integers following the below 2 constraints:
(a) the minimum and maximum value for each random value:
(i) 25 ≤ random_val_1 ≤ 30
(ii) 25 ≤ random_val_2 ≤ 30
(iii) 17 ≤ random_val_3 ≤ 20
(iv) 5 ≤ random_val_4 ≤ 10
(v) 8 ≤ random_val_5 ≤ 10
(b) sum(random_val_1, random_val_2, random_val_3, random_val_4, random_val_5) should be equals N
The output should be in the following form:
[ <int> random_val_1, <int> random_val_2, <int> random_val_3, <int> random_val_4, <int> random_val_5 ]
I was able to generate random values and only pass the residue of the given input N to the remaining random values to satisfy constraint (b) but not (a)
CodePudding user response:
We can see that for the given values, generating all possible solutions and randomly picking one won't take much time, as there are atmost (30 - 25 1) * (30 - 25 1) * (20 - 17 1) * (10 - 5 1) * (10 - 8 1) = 2592
possibilities.
For generating the numbers, we can observe that N cannot be less than the sum of all minimum constraint at each index. We can use this fact to recursively reduce the search space and generate the numbers.
Here's an implementation in C .
Note that we can move the "random generation part" for picking the value at each index, instead of randomly picking one from all possible solutions, as in the former case, on average the runtime would be faster than the latter method (depending on the random generation method used).
CodePudding user response:
So N is between 80 and 100. If N is 80 there is nothing to sample, same if N=100.
If N is set to something in the range [81...99], then find mean values M1, M2, M3, M4, and M5 still within the constrain (a) and summed to N.
Then find probabilities
p1 = M1/N, p2=M2/N, ...
Then use your favorite Multinomial distribution sampling routine with probabilities p1, p2, ...p5, and N as sum, and reject any sample that violates (a).
(b) would be satisfied automatically cause of distribution properties