Originally posted to SOAPitStop.com, Jun 25, 2008.
I am sure this is covered somewhere on the great big Internet, but it’s new to me. And it sucked until I discovered what the problem was. Basically, I had random values being generated that were anything but random. “Oh, you forgot to set a seed value to something pseudo-random like now.millisecond.” No. That didn’t help. Check out this code and see what the results are:
Private Sub UnRandom() Dim r As New Random(Now.Millisecond) Dim winCount, winCount2 As Integer For i As Integer = 1 To 100 If Rndm() > 50 Then winCount += 1 Next For i As Integer = 1 To 100 If r.Next(1, 100) > 50 Then winCount2 += 1 Next MsgBox(winCount & ":" & winCount2) End Sub Private Function Rndm() As Integer Dim r As New Random(Now.Millisecond) Return r.Next(1, 100) End Function
Assuming a 50/50 chance of win, you would expect that a Random.Next would return a random value. Seemingly not when it gets continually instantiated like in the Rndm function. So this apparently is not a case where you want all of your variables to be contained in their own methods. You’d probably want to have one single random number generator for your whole application.