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.
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.
This program will attempt to give you the answer. But because you are dealing with random numbers, there is the possibility that this will never give you the answer.
There is no guarrentee that 30 random numbers from 1-9 would add up to any specific N.
What you can find is a list of numbers which will add up to N and are bounded from 1-9 but the number will not be 30 necessarily. I believe the minimum number of numbers you need is 23, being (22*9) + 2. The maximum of course will be 200 (200*1). So the length of the list is somewhere inside [23,200]. The chances that a random list may be length 30 is thus quite low. If all list lengths are obtainable (i think they are) your chances in the long run at about 0.5%.
If you want an unbiased algorithm then the naive implementation is something like:
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.
If statistical bias from true randomness is acceptable, you can add numbers up to N - [max random number], then select the last number as N - sum(selected so far).
I think this is the simplest way to do it, so it may lack some sophistication however it will get you there.
Hope it helps!
I'm not sure what the statistics are on this but, the issue here is that you don't want to randomly select a number that makes it impossible to sum N with M number of entries either by overshooting or undershooting. Here's how I would do it:
I didn't have a lot of time to test this so apologies if there's a flaw in my logic somewhere.
EDIT:
I did some testing and everything seems solid. If you want a nice pretty spread it looks like you want something along the lines of
Total = Count * ((UPPER + LOWER) / 2)
. Although I'm fairly certain that as the difference betweenUPPER
andLOWER
increases the more flexible this becomes.