0
Dim top = RandomPosition()
Dim left = RandomPosition()    
End Sub

Function RandomPosition()
    Dim rand As New Random()
    Dim number = rand.Next(1, 100)
    Return number
End Function

Hi guys I am trying to get 2 different random values (for now. Once this works I will need a few more). The problem is that with the above code top and left always equal the same random number.

cohen
  • 621
  • 1
  • 9
  • 21
  • possible duplicate of [Getting Duplicate Random Numbers](http://stackoverflow.com/questions/11769061/getting-duplicate-random-numbers) – Matt Wilko Aug 03 '12 at 08:13
  • The answers you've got address your specific problem, but be aware that even once you've fixed it, you might still *sometimes* get the same number twice in a row. Sometimes when you roll a die you get a `5` and then another `5`, after all. – AakashM Aug 03 '12 at 08:27

3 Answers3

3

You create a new random sequence every time you call RandomPosition but, because you're calling it in quick succession, they'll have the same seed (based on time). Same seed means same sequence.

You should create the rand variable once, then just continue to use it, something like:

Dim rand as New Random()
Dim top = rand.Next (1, 100)
Dim left = rand.Next (1, 100)

Alternatively, if you really want it in its own function, make the random generator static so that it maintains its state across calls:

Function RandomPosition()
    Static rand = New Random()
    Return rand.Next(1, 100)
End Function

The following complete VB2010 program shows this in action:

Module Module1
    Function RandomPosition()
        Static rand As Random = New Random()
        Return rand.Next(1, 100)
    End Function

    Sub Main()
        Dim top = RandomPosition()
        Dim left = RandomPosition()
        MsgBox("top = " & CStr(top) & ", left = " & CStr(left))
    End Sub
End Module

It outputs, on various runs:

top = 7, left = 93
top = 45, left = 90
top = 44, left = 62
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

how about making an instance static to preserve the same instance?

Public Function RandomPosition(r) As Integer
    Static rand As System.Random = New System.Random()
    Return rand.Next(1, 100)
End Function
Ambrose
  • 501
  • 3
  • 13
0

You can wait 1 millisecond before initialising the Random object.

System.Threading.Thread.Sleep(1)
Dim rand As New System.Random
DYMATEJlb
  • 29
  • 2