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

后端 未结 16 721

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 togethe

16条回答
  •  一生所求
    2020-12-15 22:47

    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.

提交回复
热议问题