0

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.

parap
  • 119
  • Is there a fixed array lenght? – jgyou Oct 21 '13 at 03:42
  • No, any length will do – parap Oct 21 '13 at 03:43
  • Then to be completely random with NO bias the best bet is to just sample the 5 variables at random uniformly untill the sum is equal or greater to X, and to reject sequences that yield a greater sum. – jgyou Oct 21 '13 at 13:30
  • Alternatively, you can compute all the sequences that give the proper sum and sample uniformly from them. It is especially efficient if you have to draw a LOT of arrays from a set certain set of numbers (however this scales very badly: Say the smallest number is 5 time as small as X, then you have $\sum_{k=1}^{5} k^k = 1, 5, 32, 288, 3413$ sums to compute) – jgyou Oct 21 '13 at 13:38

1 Answers1

0

(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

ndh
  • 430