简体   繁体   中英

Why I cannot generate more than 6551 random numbers

I have the following code in C#, inside the Main method of a Simple Console Application.

I have debuged and, after List.Count = 6551 it seems the random values repeat themselves.

List<int> list = new List<int>(9999);
bool waiting = true;
Random random = new Random(DateTime.Today.Milliseconds);

do
{
    int units = random.Next(0, 9);
    int tens = random.Next(0, 9);
    int hundreds = random.Next(0, 9);
    int thousands = random.Next(0, 9);

   int result = int.Parse(String.Format("{0}{1}{2}{3}", units, tens, hundreds, thousands));

   if(list.Contains(result))
   {
       continue;
   }
   else
   {
       list.Add(result);
   }

   if(list.Count == 9999)
   {
       waiting = false;
   }

}while(waiting);

Console.WriteLine("Finished"):
Console.ReadKey();

Your digts range from 0 to (and excluding,) 9, which makes eight choices per digit (0-8) and thus 6561 combinations ( 9*9*9*9 ).

Also, beware that your algorithm is extremely inefficient. Eventually, your list will be very crowded and then, the algorithm will spend most of the time checking whether a given random number is already contained in your result list.

If your goal is to shuffle indices, you can reach that more eficiently by keeping a list of indices you haven't inserted already.

The answer has already be given by Georg, but concerning your efficiency problem: if what you want is a shuffled list of integer, you can do it with an extension method on the list.

var shuffled = Enumerable.Range(0, 10000).Shuffle();

Look here for more info An extension method on IEnumerable needed for shuffling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM