0
for (int i = 1; i <= 55; i++ )
{
    System.Random myRandom = new System.Random();
    //int myInt; 3 lines just alternate method
    //myInt = myRandom.Next();
    //System.Console.WriteLine(myInt);
    System.Console.WriteLine(myRandom.Next());
    Thread.Sleep(15); // if less, trouble
}

I kept getting multiples of the same number, up to twenty at a time, instead of each consecutive number being different. For some reason I added the sleep statement and it works if the value is 15 or greater. In fact, if you increment the sleep argument value, you can 'select' how many consecutive repeated numbers you get. Setting a range made no difference. Is the loop faster than the random number generator? This is not serious, I am working through the book "Essential C# 5.0". I looked at least fifty "random" questions, but none covered this phenomena. The three commented lines are a different way to do the same thing, I did not execute both in the same build.

Himal
  • 1,351
  • 3
  • 13
  • 28
  • 2
    The reason is that you're creating a new instance of Random every time. See this question for details: [Random number generator only generating one random number](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Avner Shahar-Kashtan Nov 09 '14 at 06:00

1 Answers1

1

The problem lies in this line:

System.Random myRandom = new System.Random();

It should be outside the for-loop. Why? Because it generates a random seed based on the timing information, and as you create them one after another, they each get the same seed. When you make the thread sleep in-between the iterations, the time changes enough so that the next Random gets a different seed value.

Try this instead:

System.Random myRandom = new System.Random();
for(int i = 1; i <= 55; i++)
{
    // Here be the rest of the code
}

Now, the Random object is created just once, getting its seed value just once.

manabreak
  • 5,415
  • 7
  • 39
  • 96