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

后端 未结 16 716

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:31

    The problem is we want all numbers to be bounded 1-9 and add up to N. So we have to generate each number one by one and determine the real bounds for the next number.

    This will of course generate statistical bias toward the end of the list, so I recommend shuffling the array once after generating.

    To determine the next number's bounds, do the following: Upper bound = take the remaining sum minus (the number of elements remaining * min). Lower bound = take the remaining sum minus (the number of elements remaining * max).

    Something like (untested):

    public static List RandomList(int digitMin, int digitMax, 
                                       int targetSum, int numDigits)
    {
        List ret = new List(numDigits);
    
        Random random = new Random();
        int localMin, localMax, nextDigit;
        int remainingSum = targetSum;
    
        for(int i=1; i<=numDigits; i++)
        {
              localMax = remainingSum - ((numDigits - i) * min);
              if(localMax > max)
                  localMax = max;
    
              localMin = remainingSum - ((length - i) * max);
              if(localMin > min)
                  localMin = min;
    
              nextDigit = random.Next(localMin, localMax);
              ret.Add(nextDigit);
              remainingSum -= nextDigit;
        }
    
        return ret;
    }
    

    The idea here is as you generate numbers, the range of possible values for the remaining numbers gets smaller, like a limit function zeroing in on a target sum. Sort of.

    Edit: I had to change the for loop to be 1-based, because we want the number of elements left AFTER generating this one.

    Edit2: Put it in a method for completeness and changed length to be numDigits for readability.

提交回复
热议问题