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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
Mechanism

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 GetRandomNumber function returns a random number from the Num array list and also removes it from there. When all the numbers have been poped (not to be confused with stack poping) out, the Num array list is re-filled with the values in NumDomain and the cycle continues. Thus, allowing no repeats per cycle.

No votes yet.
Please wait...