Random Numbers

hog

Senior Contributor
Joined
Mar 17, 2003
Messages
984
Location
UK
I'm trying to get 9 numbers from 0 to 8 using this

Visual Basic:
intButtonNumber = CInt(Int((8* Rnd())))

I am then testing using an array if the random number has already come out and if so loop until an unpicked number appears.

Trouble is it stays in the loop forever, numbers like 4, 6 and 3 keep repeating?

Any ideas please?:(
 
The random numbers will never use the complete range provided, you will probably end up writing some fiddily code on, try adding 1 to the number drawn until its one that hasn't been chosen, if it exceeds nine then return to 0 and keep trying
 
I thank you :-)

Visual Basic:
For intX = 0 To 8

    Do While True

                intButtonNumber = CInt(Int((8 + 1) * Rnd()))

                If intButtonNumber < 9 AndAlso intButtonsSet(intButtonNumber) = 0 Then

                    DirectCast(m_htControlsHashTable("Button" & intX + 1), Button).Location = intZones(intButtonNumber)

                    intButtonsSet(intButtonNumber) = -1

                    Exit Do

                End If

      Loop

Next
 
I wouldn't use the Rnd() function anymore. It's another holdover from VB6 that's been replaced by the FAR better Random object.

Visual Basic:
Dim i As Int32
Dim r As Random = New Random()
For i = 0 To 99
    System.Diagnostics.Debug.WriteLine(i & " " & r.Next(0, 10))
Next

There are other overloads for the Next method. There are also other methods (NextDouble and NextBytes).

You'll still have to add 1 to the Max just as before. So for a range of numbers 0-9, use .Next(0, 10).

-Nerseus
 
Nice one...

Tell me, is there any easy way to find the new stuff in VB.NET? I somehow didn't find the Random object?

Is there a good method to use or am I just not looking right :-(
 
I use the Object browser's Search button. Press Ctrl-Alt-J for the object browser (or reassign to F2 like it was in VB6 :)), then press the little binocular button. I've found that between that and scouring the built-in MSDN help, I find a ton of useful stuff.

Plus, working in a team that's been using .NET for almost a year (in production, more if you count playing around), we share a lot of useful tidbits.

-Nerseus
 
Back
Top