Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: random number issue

Tags:

c#

random

See the following:

   for (int i=0; i<2; i++) {
        // do some stuff
        r = new Random((int)DateTime.Now.Ticks);
        iRandom = r.Next(30000);
        // do some other stuff
   }

Don't ask me how, but iRandom is sometimes the same for both iterations of the loop. I need iRandom to be different for each iteration. How do I do this?

like image 865
Craig Johnston Avatar asked Aug 28 '26 08:08

Craig Johnston


1 Answers

Change your loop to this:

    r = new Random((int)DateTime.Now.Ticks);

   for (int i=0; i<2; i++) {
    // do some stuff
    iRandom = r.Next(30000);
    // do some other stuff
   }

In other words, put the creation of the Random object outside the loop.

like image 118
Flipster Avatar answered Aug 29 '26 22:08

Flipster