Option Explicit 'Force variable declaration
Private Declare Function GetTickCount Lib "kernel32" () As Long 'The GetTickCount
'function retrieves
'the number of
'milliseconds that
'have elapsed since
'Windows was started.
Private Sub Form_Load()
Dim Ar(1 To 10000) As Integer 'The array to store it in
Dim i, j As Integer 'Counters for loops
Dim X As Integer 'Variable to store the random generated number
Dim bFound As Boolean 'Boolean to check if the value has been generated before
Dim S As Long 'Variable to store the number of milliseconds that have elapsed since
'Windows was started when we begin the task
Randomize 'Just once to ensure that we get random values
S = GetTickCount 'Store the number of milliseconds that have elapsed since Windows was started when we begin the task
For i = 1 To 10000
Do 'Start the loop that generates a random number and checks if it has already been generated
X = RandomInteger(1, 10000) 'Generate a random number
bFound = False 'Set the boolean to false, if we find the number while searching the array, we'll set it to true which means that we already have that number
For j = 1 To i 'We only need to check up to i (since we haven't put any values in the rest of the array)
If Ar(j) = X Then 'If an item of the arrray is the same as the last generated number
bFound = True 'Set the boolean to true (it already exists)
DoEvents 'To not freeze until the looping is done
Exit For 'Since we found it there is no need to check the rest
End If
Next
Loop Until bFound = False 'If it wasn't found then we'll add it, if it was found then we go back to generating a new number and comparing it with all the items of the array
Ar(i) = X 'Add it to the array
Next
'At the end we will subtract the number of milliseconds that had elapsed
'when the task started from the number of milliseconds that have elapsed
'when the task is complete and show it in the form's caption
Me.Caption = GetTickCount - S
ShowInTextBox Text1, Ar 'Just to print the data and see it
End Sub
Private Function RandomInteger(Lowerbound As Integer, Upperbound As Integer) As Integer 'The random number generator code
RandomInteger = Int((Upperbound - Lowerbound + 1) * Rnd + Lowerbound)
End Function
Private Sub ShowInTextBox(TB As TextBox, A() As Integer) 'Just a sub to show the data in a textbox
Dim i As Integer
TB.Text = ""
For i = 1 To UBound(A)
TB.Text = TB.Text & CStr(A(i)) & vbCrLf
DoEvents
Next
TB.Text = Left$(TB.Text, Len(TB.Text) - 2)
End Sub