tags:

views:

32

answers:

3

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?

A: 

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())
Zaid Zawaideh
+1  A: 

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.

devoured elysium
Yup. It uses the current clock tick to seed the randomizer. That tick doesn't change very fast (15.625 msec).
Hans Passant
+1  A: 

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'
Chris Haas
This solution worked, declaring it as `Static` solved it.
Cyclone