|
-
Dec 2nd, 1999, 03:39 PM
#1
Thread Starter
Junior Member
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.
------------------
[email protected]
-
Dec 2nd, 1999, 04:21 PM
#2
Addicted Member
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
-
Dec 2nd, 1999, 04:22 PM
#3
Hyperactive Member
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.
[email protected]
-
Dec 2nd, 1999, 04:48 PM
#4
Thread Starter
Junior Member
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
------------------
[email protected]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|