0

I am going to generate 100 random numbers in a for loop. The only problem is that since the random() method is timer-based, it will generate the same numbers 3-4 times in a row. I can solve this problem by including a threat.sleep() method in my loop. Therefor i want to know the exact refresh rate of the random() method so that i can match the threat.sleep() method and not get delayed more than necessary.

Here is my code:

for (int i; i <= 100; i += 1)
{        
    Random rndNum = new Random();
    Console.WriteLine(rndNum.Next(1, 100));
    Thread.Sleep(X); //I want to know the best value of X (as less delay as possible) 
}

Thanks a bunch

/HamMan4Ever

augu0454
  • 45
  • 7

2 Answers2

1

I've never heard or read that the Random class is timer-based. You may have heard that it is seeded by the system time, but after that each call to Next will return a randomish number typically different from the previous. Typically when you see non-random data coming from a Random, it's because you're creating a new random on each iteration through a loop, as you are in the code you shared. Since each is seeded from the system clock and you're creating several very quickly, you see repeated patterns. Create your Random outside the loop to make this problem go away.

adv12
  • 8,443
  • 2
  • 24
  • 48
0

It is equal to the refresh rate of the system clock as it uses the time as a seed. But for your job, you should keep the Random instance outside the loop.

Random rndNum = new Random();
for (int i; i <= 100; i += 1)
{        
    Console.WriteLine(rndNum.Next(1, 100));
}

Since it uses the time as a seed, it uses it only ones and will generate random numbers even if you call it multiple times at the same time as long as you use the same instance.

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • Saying that the refresh rate matches the system clock is misleading and feeds OP's incorrect notion that there is such a thing as a refresh rate when invoking the methods on the `Random` class. There is not. – sstan Dec 21 '15 at 21:50
  • While there is no refresh rate, because it uses the system time, the refresh rate will match the rate at which the time is updated. – Fᴀʀʜᴀɴ Aɴᴀᴍ Dec 21 '15 at 21:51
  • I'm not sure we have the same definition of *refresh rate*. – sstan Dec 21 '15 at 21:53