Thread: Random Numbers
View Single Post
Old 05-13-2002, 01:23 PM
BillSoo's Avatar
BillSoo BillSoo is offline
Code Meister

Retired Moderator
* Guru *
Join Date: Aug 2000
Location: Vancouver, BC, Canada
Posts: 10,441
Default How to generate non-repeating random numbers

The there are 2 basic methods for creating non-recurring random numbers.

1) Generate a random number. Check it against a list of numbers already generated. If it exists, get another one. If it does not, add it to the list.

2) Generate a list of all possible numbers,in sequence. Use the random number generator to mix them up.

Both methods have their advantages and disadvantages and the method you use depends upon your situation. If you are shuffling a deck of cards, you would use the second method. Otherwise, as the number of available cards diminishes, you spend most of your time generating invalid entries. Conversely, if you were generating positions of objects in a large universe, you would use the first method since you don't arn't going to generate all possible values, just a few.

Here is some code to demonstrate the two methods:

Private Function CreateRandom(ByVal num As Long, ByVal min As Long, ByVal max As Long) As Variant
'returns an array of numbers between where min <= x < max
'returns NULL if there is a problem
Dim aValues() As Long
Dim i As Long, x As Long, span As Long, j As Long, bFound As Boolean
span = max - min + 1
If (span > num) And (num > 0) Then
    ReDim aValues(num - 1)
    For i = 0 To num - 1
            x = Int(Rnd() * span) + min
            bFound = False
            For j = 0 To i - 1
                If x = aValues(j) Then bFound = True: Exit For
            Next j
        Loop While bFound
        aValues(i) = x
    Next i
    CreateRandom = aValues
    CreateRandom = Null
End If
End Function

Private Function ShuffleArray(aData As Variant) As Boolean
'shuffles array adata. Returns true unless there is a problem
Dim max As Long
Dim i As Long, j As Long, v As Variant

If IsArray(aData) Then
    max = UBound(aData)
    For i = max To 1 Step -1
        j = Int(Rnd() * (i + 1)) 'pick one to switch
        If i <> j Then
            v = aData(i)
            aData(i) = aData(j)
            aData(j) = v
        End If
    Next i
    ShuffleArray = True
End If
End Function
"I have a plan so cunning you could put a tail on it and call it a weasel!" - Edmund Blackadder
Reply With Quote