1

Possible Duplicate:
Random number generator only generating one random number

In vb.net I am using this function to get random numbers:

  Private Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
    Dim Generator As System.Random = New System.Random()
    Return Generator.Next(Min, Max)
  End Function

I am calling the GetRandom function several times from another function which looks like this (simplified):

Public Sub GetRandomPerson() 
  Dim Gender as integer
  Dim Zip as integer

  Gender = GetRandom(1,3)
  Zip = GetRandom(10000, 99999)

  ' Here I save the random person to DB
End Sub

And then I have this

For i As Integer = 1 to 10000
  GetRandomPerson()
Next

My problem is that there seems to be a dependency on calls to GetRandom, it seems that if Gender is 1 then Zip will never be higher than a certain value (around 5000) and if Gender is 2 then Zip will always be higher than a certain value (around 5000).

Why is that, what am I missing?

Community
  • 1
  • 1
Muleskinner
  • 14,150
  • 19
  • 58
  • 79
  • Try it by taking the `Dim Generator As System.Random = New System.Random()` out of the function – L.B Nov 16 '12 at 12:24
  • @J. Steen After reading the other answer I agree and it gave me the solution / should I delete my question? – Muleskinner Nov 16 '12 at 12:33
  • @Muleskinner If you feel it doesn't contribute to the stackoverflow community, delete it. If you feel there's extra information that's invaluable, don't delete it. =) – J. Steen Nov 16 '12 at 12:36

1 Answers1

2

You are instantiating Random on every call. This is why you are getting the results you are seeing:

Dim Generator As System.Random = New System.Random()

Random uses a seed based on the current time to generate a pseudo random sequence (which, if has the same seed, will generate the same sequence) - if called in a loop as you do, there can be 0 change in the seed, generating the same values over and over.

Move the instance outside of the function, so you only ever use a single instance of the generator.

I suggest reading this article by Jon Skeet about Random.

Oded
  • 489,969
  • 99
  • 883
  • 1,009