Connecting Tech Pros Worldwide Forums | Help | Site Map

Non-repeating random numbers

Moderator
 
Join Date: Oct 2006
Location: Australia
Posts: 7,748
#1   Jul 3 '07
This is a simple VB6 function to generate random numbers in the specified range, without repeating any numbers.

New, and only briefly tested. Use at your own risk. :)

Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2.  
  3. Private UsedNumber As New Collection
  4. Private Const MaxAttempts As Long = 150
  5. Private Const Zero As Long = 0
  6. Private Const One As Long = 1
  7.  
  8. Public Function RandomNonRepeatingBetween(ByVal LowerLimit As Long, ByVal UpperLimit As Long) As Long
  9.   ' Generate a pseudo-random number between the specified bounds.
  10.   ' Never return one which has already been used.
  11.   ' Don't forget to use Randomize at least once before calling
  12.   ' this function (but not EVERY time, if calling repeatedly).
  13.  
  14.   ' The record of used numbers will be cleared only when the
  15.   ' caller specifically requests it by passing zero as both the
  16.   ' upper and lower bounds.
  17.  
  18.   ' If it is not possible to satisfy the request (for instance,
  19.   ' if all numbers in the requested range have already been
  20.   ' used, then error 17 ("Can't perform requested operation")
  21.   ' will be raised. Caller should allow for this and handle
  22.   ' it as appropriate.
  23.  
  24.   ' Note, for the moment it will simply try up to 150 times, I
  25.   ' haven't worked out the code yet to do a proper check for
  26.   ' whether any numbers are left in the range.
  27.  
  28.   ' If lower/upper limit are backward, swap them around.
  29.   Dim Temp As Long
  30.   Dim Attempts As Long
  31.  
  32.   If LowerLimit > UpperLimit Then
  33.     Temp = LowerLimit
  34.     LowerLimit = UpperLimit
  35.     UpperLimit = Temp
  36.   End If
  37.  
  38.   ' Clear memory if caller requests it.
  39.   If LowerLimit = Zero And UpperLimit = Zero Then
  40.     Do While UsedNumber.Count > Zero
  41.       UsedNumber.Remove One
  42.     Loop
  43.   End If
  44.  
  45.   On Error Resume Next
  46.   Do
  47.     Temp = LowerLimit + Rnd * (UpperLimit - LowerLimit)
  48.     UsedNumber.Add Temp, Format(Temp)
  49.     If Err.Number = Zero Then
  50.       RandomNonRepeatingBetween = Temp
  51.       Exit Do
  52.     End If
  53.     Err.Clear
  54.     Attempts = Attempts + One
  55.   Loop While Attempts < MaxAttempts
  56.   Err.Clear
  57.   On Error GoTo 0
  58. End Function



Closed Thread


Similar Visual Basic 4 / 5 / 6 bytes