Cyclone
Cyclone

Reputation: 18295

Randomize() in vb.net not randomizing properly

What is wrong with this code? It is called in groups of four, and always seems to wind up with only two combinations:

Public Function GetRand() As String
        Randomize()
        Dim r As Integer = CInt(Rnd() * 3)
        Select Case r
            Case 0
                Return str1
            Case 1
                Return str2
            Case 2
                Return str3
            Case 3
                Return str4
            Case Else
                Return str1
        End Select
    End Function

It is returning random strings, but it seems to be returning them in a non-random order?

Upvotes: 0

Views: 1429

Answers (3)

devoured elysium
devoured elysium

Reputation: 105037

The problem probably is the call to Randomize(). Take it out and it should work fine. When calling Randomize(), you are setting the seed the random number generator will use. You should only call it once, otherwise you might be seeding it always with the same value.

Upvotes: 1

Chris Haas
Chris Haas

Reputation: 55417

Definately chaeck out the Random object that @zawaideh mentions:

    Static R As New Random()  'Static so that it only gets initialized once'
    R.Next(0, 4)              'Returns an integer from zero up to but not including 4, so 0,1,2,3'

Upvotes: 1

zzawaideh
zzawaideh

Reputation: 2011

If you're using VB.Net you can use the .net random number generator

Dim random_object As New Random()
Console.WriteLine(random_object.Next().ToString())

Upvotes: 0

Related Questions