Alex Rivera | Logout

Generate a series of random numbers that add up to N in c#

Asked 2009-01-23T05:47:41.070
14

How do I generate 30 random numbers between 1-9, that all add up to 200 (or some arbitrary N), in C#?

I'm trying to generate a string of digits that can add together to be N.

Edit
Report

1 Answer

0

If you want an unbiased algorithm then the naive implementation is something like:

while (true) {
  numbers = [];
  total = 0;
  for (i = 0; i < COUNT; ++i) {
    next = rand(BOUNDS);
    total += next;
    numbers.push(next);
  }

  if (total == TARGET) {
    return numbers;
  }
}

This is non-terminating and slow but it is not biased. If you want a unbiased algorithm I'm not convinced the algorithms posted here are unbiased.

answered 2009-01-23T15:04:34.020

Your Answer