|
|
Title | Randomize a list of names in Visual Basic 6 |
Description | This example shows how to randomize a list of names in Visual Basic 6. |
Keywords | randomize, random, list of names, name list, Split, Rnd, Visual Basic 6 |
Categories | Algorithms |
|
|
I recently used this program to select random people to receive free books.
Enter the list of names that you want to randomize in the Split statement.
The program uses Split to break the names apart and put them in an array. It then randomizes the array.
(For each position i in the array except the last one, the program randomly picks an index j between i and the end of the array. It then swaps the item at position j into position i.)
The program then displays the list in its randomized order.
|
|
Private Sub cmdRandomize_Click()
Dim names() As String
Dim i As Integer
Dim j As Integer
Dim tmp As String
Dim txt As String
' Put the names in an array.
names = Split("Alice;Ben;Cindy;Dan;Erica;Frank", ";")
' Randomize the array.
Randomize
For i = LBound(names) To UBound(names) - 1
' Pick a random entry.
j = Int((UBound(names) - i + 1) * Rnd + i)
' Swap the names.
tmp = names(i)
names(i) = names(j)
names(j) = tmp
Next i
' Display the results.
For i = LBound(names) To UBound(names)
txt = txt & vbCrLf & i & ": " & names(i)
Next i
txt = Mid$(txt, Len(vbCrLf) + 1)
txtResults.Text = txt
End Sub
|
|
To pick N names from the list, simply use the first N as they are presented randomly.
|
|
|
|
|
|