08 Feb, 2007 · 2 minutes read
Sometimes, we require to generate non-repeating random numbers. Here’s the code I wrote to do just that. The numbers to be generated can be within the specified range or passed as a param array.
Public Class RandomNumber
Dim NumDomain As New ArrayList ' The Numbers to be generated
Dim Nums As New ArrayList ' The Numbers waiting to be generated
Sub New(ByVal Start As Integer, ByVal Finish As Integer)
' Sequential Numbers
Dim I As Integer
For I = Start To Finish
NumDomain.Add(I)
Next
AddItems()
End Sub
Sub New(ByVal ParamArray Numbers() As Integer)
' Numbers in a Param Array
Dim Number As Integer
For Each Number In Numbers
NumDomain.Add(Number)
Next
AddItems()
End Sub
Private Sub AddItems()
Nums.Clear()
' Insert All Numbers Into the Array
Dim I As Integer
For I = 0 To NumDomain.Count - 1
Nums.Add(NumDomain(I))
Next
End Sub
Public Function GetRandomNumber() As Integer
If Nums.Count = 0 Then
' Re-add the Items, when all the numbers have been generated.
AddItems()
End If
' Return a Random Item and Remove it from the List
Dim Ch As Integer
' Using Timer as the seed for the Random Number Generation
Randomize(Microsoft.VisualBasic.Timer)
' Random Number is generated within the range.
Ch = 0 + CInt(Rnd() * (Nums.Count - 1))
Dim Num As Integer = Nums(Ch)
Nums.RemoveAt(Ch)
Return Num
End Function
End Class
The overloaded constructors allow numbers to be generated either within a range or from the numbers passed as parameters. Internally there are two array lists: NumDomain& Num. The former contains all the numbers within the domain and the latter holds the numbers that have not been generated. The GetRandomNumberfunction returns a random number from the Numarray list and also removes it from there. When all the numbers have been poped (not to be confused with stack poping) out, the Numarray list is re-filled with the values in NumDomainand the cycle continues. Thus, allowing no repeats per cycle.