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
After all the discussions here, there's one other way to generate a list that doesn't introduce bias. Yes, it does differ from what the question is asking, but instead of randomly choosing digits, you can randomly increment digits until you reach the sum. Like the following (again untested):
public static List RandomListByIncrementing(int digitMin, int digitMax,
int targetSum, int numDigits)
{
if(targetSum < digitMin * numDigits || targetSum > digitMax * numDigits)
throw new ArgumentException("Impossible!", "targetSum");
List ret = new List(Enumerable.Repeat(digitMin, numDigits));
List indexList = new List(Enumerable.Range(0, numDigits-1));
Random random = new Random();
int index;
for(int currentSum=numDigits * digitMin; currentSum
The idea here is you keep a list of references to your number list. Choose a reference at random, and increment the corresponding number. If you can't increment it anymore, remove the reference so you don't choose it next time.
Now there's no shuffling business to be done at the end of the day, although arguably this will still produce one of the available sets of answers to the question and it's a question of which one "feels better" or is faster to run.