Given a Sum, How to Randomly Generate Variables

68 Views Asked by At

I have five variables:

A=2
B=3
C=4
D=5
E=6

I want to create a random array of these variables so that their sum equals a given number X.

Example if X=21, a possible output would be {D,B,A,D,E}. Note that variables may be used more than once or not at all. Thanks.

1

There are 1 best solutions below

0
On

(1) Choose A,B,C,D, or E randomly
(2) Count how many times the value for that number fits in X (i.e. $\lfloor\frac{X}{A,B,C,D,E}\rfloor$)
(3) Choose a random number between 0 and the value from (2), inclusive
(4) Multiply the A,B,C,D, or E value by that number
(5) Subtract the value from (4) from X
(6) Recurse back to (1) with the value from (5) replacing X, and the chosen variable from (1) removed from the five options
(7) When X=0, finish. Note that there is a situation that X is smaller than all of your five values (e.g. X=1). If that is the case, redoing everything is the simplest solution