|
|
Title | Randomize an array |
Description | This example shows how to randomize an array in Visual Basic 6 using the unsorting algorithm described in my book "Ready-ro-Run Visual Basic Algorithms." |
Keywords | array, random, randomize |
Categories | Algorithms |
|
|
This program uses the unsorting algorithm described in my book Ready-to-Run Visual Basic Algorithms.
For each item, the algorithm randomly selects an item at that position or later in the array and swaps the two. This produces a randomized list. See my book for a proof.
|
|
' Assumes the array should be dimensioned
' as in Numbers(1 To NumItems, 1 To Max2).
Private Sub RandomizeArray()
Dim i As Integer
Dim j As Integer
Dim tmp As Integer
' Randomize the array.
Randomize
For i = 1 To NumItems - 1
' Pick a random entry.
j = Int((NumItems - i + 1) * Rnd + i)
' Swap the numbers.
tmp = Numbers(i)
Numbers(i) = Numbers(j)
Numbers(j) = tmp
Next i
End Sub
|
|
|
|
|
|