Random Numbers

hog

Well-known member
Joined
Mar 17, 2003
Messages
984
Location
UK
Im trying to get 9 numbers from 0 to 8 using this

Code:
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 hasnt been chosen, if it exceeds nine then return to 0 and keep trying
 
I thank you :-)

Code:
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 wouldnt use the Rnd() function anymore. Its another holdover from VB6 thats been replaced by the FAR better Random object.

Code:
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).

Youll 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 didnt find the Random object?

Is there a good method to use or am I just not looking right :-(
 
I use the Object browsers 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. Ive found that between that and scouring the built-in MSDN help, I find a ton of useful stuff.

Plus, working in a team thats 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