Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating 5 random numbers with a given limit N, along with per random value constraint

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)

like image 498
StackUnderflow Avatar asked Dec 04 '25 01:12

StackUnderflow


1 Answers

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

like image 68
sharpnife Avatar answered Dec 06 '25 17:12

sharpnife



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!