Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleRandomize an array
DescriptionThis 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."
Keywordsarray, random, randomize
CategoriesAlgorithms
 
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
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated