samedi 25 juillet 2015

How to create 2 Random objects in 2 consecutive lines of code with different seeds?

I want to make 2 different Random objects in 2 consecutive lines of code. The parameterless constructer of the Random class is like this:

public Random() 
    : this(Environment.TickCount) {
  }

It uses Environment.TickCount as the seed. TickCount represents the amount of time that has passed since the OS is switched on, right?

I tried the following:

Random r1 = new Random ();
Random r2 = new Random ();

And I found out that the 2 Random objects had the same seed because their Next methods return the same number each time. I was surprised by how fast a line of code can be executed. Then I tried:

long tick1 = Environment.TickCount;
for (int i = 0 ; i < 100000 ; i++) {

}
long tick2 = Environment.TickCount;
Console.WriteLine (tick2 - tick1);

And I get 0. So I iterated 100000 times and still, not even 1 millisecond has passed?

I just want to ask how can I create 2 different Random objects or is there another way to generate random numbers?




Aucun commentaire:

Enregistrer un commentaire