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 a 2-dimensional array
DescriptionThis example shows how to randomize a 2-dimensional array in Visual Basic 6 using the unsorting algorithm described in my book "Ready-ro-Run Visual Basic Algorithms."
Keywordsarray, random, randomize, 2-dimensional array
CategoriesAlgorithms
 
This program uses a modified version of 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 Max1, 1 To Max2).
Private Sub RandomizeArray()
Dim max_cell As Integer
Dim i1 As Integer
Dim j1 As Integer
Dim i2 As Integer
Dim j2 As Integer
Dim index1 As Integer
Dim index2 As Integer
Dim tmp As Integer

    ' Randomize the array.
    Randomize
    max_cell = Max1 * Max2
    For index1 = 1 To max_cell - 1
        ' Pick a random entry.
        index2 = Int((max_cell - index1 + 1) * Rnd + index1)

        ' Convert to 2-dimensional indexing.
        i1 = ((index1 - 1) \ Max2) + 1
        j1 = index1 - (i1 - 1) * Max2
        i2 = ((index2 - 1) \ Max2) + 1
        j2 = index2 - (i2 - 1) * Max2

        ' Swap the numbers.
        tmp = Numbers(i1, j1)
        Numbers(i1, j1) = Numbers(i2, j2)
        Numbers(i2, j2) = tmp
    Next index1
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated