PDA

Click to See Complete Forum and Search --> : Random Numbers


philbell
Dec 2nd, 1999, 02:39 PM
I need a snipit of code that will give me an array of random numbers within a given range without repeating any on the numbers. I also need to specify how many random numbers to generate. Is this a simple thing ??

I am stuck with this, can anyone help.

------------------
pbell@dpygb.jnj.com

Keiko
Dec 2nd, 1999, 03:21 PM
Hi philbell,

Draw one ListBox control on your form and
name it List1.
(later on, you can change the list box into
array or any other thing)

Dim intValue As Integer
Dim intFrom As Integer
Dim intTo As Integer
Dim intOuter As Integer
Dim intInner As Integer
Dim blnExist As Boolean

Randomize

intFrom = 1
intTo = 6

Me.List1 = ""
While intOuter <= (intTo - intFrom)
intValue = Int((intTo * Rnd) + intFrom)
blnExist = False
For intInner = 0 To (Me.List1.ListCount - 1)
If (Me.List1.List(intInner) = intValue) Then
blnExist = True
Exit For
End If
Next intInner
If (Not blnExist) Then
Me.List1.AddItem intValue
intOuter = intOuter + 1
End If
Wend

Does it help ?

Regards

john_murphy
Dec 2nd, 1999, 03:22 PM
To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

You will have to do the duplicate checking yourself using ascan or something similar.

John_m_murphy@hotmail.com

philbell
Dec 2nd, 1999, 03:48 PM
Thanks for your help with this. I have now got the function working. Here it is if your interested.

Private Function GetRandomNumbers(RangeStart As Integer, RangeEnd As Integer, HowMany As Integer) As Variant

Dim intValue As Integer
Dim intOuter As Integer
Dim intInner As Integer
Dim blnExist As Boolean
Dim arr() As Integer

'This will return an array with 10 random numbers between 1 and 30
'arr = GetRandomNumbers(1, 30, 10)


Randomize

ReDim arr(1)

While intOuter < HowMany

intValue = Int((RangeEnd * Rnd) + RangeStart)
blnExist = False

For intInner = 1 To UBound(arr())
If (arr(intInner) = intValue) Then
blnExist = True
Exit For
End If

Next intInner

If (Not blnExist) Then
intOuter = intOuter + 1
ReDim Preserve arr(intOuter)
arr(intOuter) = intValue
End If
Wend

'Return the array
GetRandomNumbers = arr
End Function



------------------
pbell@dpygb.jnj.com