Random Selection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi.

If I have a 'pot' of numbers 1-50 say, how would I select each of these
numbers at random until they have all been used up?

(I think I know the answer but would like a professional opinion :)

Cheers,
Steve.
 
Here is a function that returns a number between 1 and 50. It will only
return each number one time. When it has returned all the numbers, it
returns 0. After you have done the selections and want to start an new
series, use the optional argurment to restart the series.
To start a series
x= PickANumber(True)
To continue a series
x= PickANumber(Falsee)
or
x=PickANumber

I also put in comments to show where modification is necessary if you want a
number other than 50

Public Function PickANumber(Optional ByVal Restart As Variant) As Integer
Static aryNumbers(49, 1) 'Modify Here for a different number of numbers
Static blnNotFirstTime As Boolean
Dim lngX As Long
Dim intNewNumber As Integer
Dim blnNewList As Boolean

If IsMissing(Restart) Then
blnNewList = False
Else
blnNewList = Restart
End If

If blnNewList Or Not blnNotFirstTime Then
For lngX = 0 To 49 'Modify Here for a different number of numbers
aryNumbers(lngX, 0) = lngX + 1
aryNumbers(lngX, 1) = False
Next lngX
End If
intNewNumber = 0
Randomize
lngX = 0
Do While True
intNewNumber = Int((50 * Rnd) + 1) 'Modify Here for a different
number of
numbers
If aryNumbers(intNewNumber - 1, 1) = False Then
aryNumbers(intNewNumber - 1, 1) = True
PickANumber = intNewNumber
Exit Do
End If
lngX = lngX + 1
If lngX > 50 Then 'Modify Here for a different number of numbers
Exit Do
End If
Loop
blnNotFirstTime = True
End Function
 
FBxiii said:
Hi.

If I have a 'pot' of numbers 1-50 say, how would I select each of these
numbers at random until they have all been used up?

(I think I know the answer but would like a professional opinion :)

Cheers,
Steve.

This is called a "random permutaion". Below is an algorithm (dating
back to 1964!). Use it this way:

Dim aPerm As Variant
Dim i As Integer

aPerm = RandomPermutation(50)

For i = 1 To 50
Debug.Print aPerm(i)
Next

HTH
Mtthias Kläy
--
www.kcc.ch


Public Function RandomPermutation(ByVal N As Long) As Variant
'---------------------------------------------------------------------------------------
' Random permutation of numbers 1 to N.
' Durstenfeld R., Random Permutation. CACM July 1964 No. 7, p. 420
'

Dim aItem As Variant
Dim i As Long
Dim k As Long
Dim j As Long

' Fill array aItem with numbers 1 to N
ReDim aItem(1 To N) As Long
For i = 1 To N
aItem(i) = i
Next

' Initialize the random number generator
Randomize

' Permute
For i = N To 2 Step -1
j = CLng(Int(CDbl(i) * Rand)) + 1
k = aItem(i)
aItem(i) = aItem(j)
aItem(j) = k
Next

RandomPermutation = aItem

End Function
 
Back
Top