1

Possible Duplicate:
Why does it appear that my random number generator isn't random in C#?

Dear friends

I want to generate 4 random number between 1 - 55 ,but the problem is that most of the time I receive 2 number same :( for example the generated number is 2 2 5 9 or 11 11 22 22! I dont know why? I use :

Random random = new Random();
return random.Next(min, max);

for generating my random number. I put them in a While for repeating 4 times. Any Idea?Would u help me plz?

Community
  • 1
  • 1
Amir
  • 1,919
  • 8
  • 53
  • 105
  • 1
    Don't recreate the `random` object - reuse a single instance. See [Why does it appear that my random number generator isn't random in C#?](http://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c) – Michael Petrotta Oct 08 '10 at 03:28
  • That's the problem with randomness: you can never be sure if it's being unusually "unrandom," or truly random. – rovaughn Oct 08 '10 at 03:31

2 Answers2

4

You should create just one Random() object and reuse it instead of creating a new one for each random number you generate.

The reason is that every time you create a new Random object it seeds itself from the current time. If you create multiple Random objects within a short period of time then then they will seed with the same time, and so they will generate the same numbers.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

When you create a new Random() without specifying a seed, it seeds it using the current system time.

I don't remember off the top of my head the precision it uses (ticks? milliseconds?) but if you create new Random objects and use them in quick succession, they could easily have the same seed and thus return the same results.

Create one new Random(), and call .Next(min, max) on it repeatedly.

Carson63000
  • 4,215
  • 2
  • 24
  • 38