cohen
cohen

Reputation: 621

VB random function returns same value twice

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.

Upvotes: 0

Views: 3724

Answers (3)

DYMATEJlb
DYMATEJlb

Reputation: 97

You can wait 1 millisecond before initialising the Random object.

System.Threading.Thread.Sleep(1)
Dim rand As New System.Random

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881463

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

Upvotes: 3

Ambrose
Ambrose

Reputation: 511

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

Upvotes: 0

Related Questions