Two dimensional array shuffle

NavyDavey used Ask the Experts™
I'm creating a two dimensional array for storing eight .gif file names and their corresponding descriptions. The array has 16 elements, so consequently each file and description will stored in two elements.

What I need to know is how to shuffle the array using a For/Next Loop. It will loop once for each element in the array(16 times). Inside the loop I need to generate two random numbers between 1 and 16 and swap the file names and descriptions found in those row positions in the array.

How can I do this?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try this

Dim eleA,eleB,nCount,nSwap

for nCount = 1 to 16 'or 0 to 15 ?? or 0 to ubound(ar)
nSwap = cint(rnd*16 +1)
eleA = Ar(nswap,0)
eleB = ar(nswap,1)
ar(nswap,0) = ar(ncount,0)
ar(nswap,1) = ar(ncount,1)
ar(ncount,0) = eleA
ar(ncount,1) = eleB
Question:  Why use a two dimensional array?  Why not make a single dimension array of a userdefined type that contains both the file name and description (this is a manual look at it)

type FileInfo
  sName as string
  sDesc as string
end type

dim aFiles(0 to 16)
dim tFileInfo as FileInfo
tFileInfo.sName = "test0"
tFileInfo.sDesc = "test0Desc"

aFiles(0) = tFileInfo

tFileInfo.sName = "test1"
tFileInfo.sDesc = "test1Desc"

Then simply use a single dimensioned shuffle such as shown in

aFiles(1) = tFileInfo
I had some trouble trying to figure out what you were asking so I made two examples just in case I was wrong in one :)

What this does is randomly rearrange all 8 of your rows. Meaning that while the order of your rows changes the filenames and descriptions stay with each other.

'-----Code 1----
Dim myArray(8, 2) As String
Dim x As Integer
Dim iRnd As Integer
Dim tmpRow(2) As String

'Assign your values here

For x = 1 To 8
    iRnd = (Rnd * 7) + 1 '(0 to 7) + 1 = (1 to 8)
    tmpRow(1) = myArray(x, 1)
    tmpRow(2) = myArray(x, 2)
    myArray(x, 1) = myArray(iRnd, 1)
    myArray(x, 2) = myArray(iRnd, 2)
    myArray(iRnd, 1) = tmpRow(1)
    myArray(iRnd, 2) = tmpRow(2)
'----End Code 1----

What this does is randomly rearrange all the elements. Meaning that the filenames and descriptions are moved independently and randomly but they remain in the correct coloums.

'----Code 2---
Dim myArray(8, 2) As String
Dim x As Integer
Dim iRnd As Integer
Dim tmpStr As String
Dim i As Integer

'Assign your values here

For x = 1 To 8
    For i = 1 To 2
        iRnd = (Rnd * 7) + 1
        tmpStr = myArray(x, i)
        myArray(x, i) = myArray(iRnd, i)
        myArray(iRnd, i) = tmpStr
'----End Code 2----

Hope this helps

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial