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

后端 未结 16 740

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

    public static List getNumbers(int n)
        {
            Random random = new Random(DateTime.Now.Millisecond);
            List obtainedNumbers = new List(); 
            do
            {
                obtainedNumbers.Add(random.Next(1, 9));
            }
            while (n - obtainedNumbers.Sum() > 0);
            return obtainedNumbers;
        }
    

    JaredPar code likes me but its slow, it's like to throw a coin and hope to get the n value.Nice pieces of codes

提交回复
热议问题