Single-Dimension Array Reordering

The following code lists the contents of an array in a hard-coded order. Next, the array is randomly reordered and displayed. (Refresh the page to see the values change!)

The Hard-Coded Array Display

The Randomly Reordered Array Display

The ReOrdering Code:
Function JumbleArray(aArray)

  Dim iCount
  iCount = UBound(aArray)

  'Create a string of indexes
  Dim iLoop, strIndex, iUpper, iLower
  iLower = LBound(aArray)

  For iLoop = iLower to iCount
    strIndex = strIndex & CStr(iLoop)

    If iLoop < iCount then strIndex = strIndex & ","

  'Choose a Random Index
  Randomize Timer

  Dim iRnd, aTmp, iTmpUpper, strNewIndex
  Redim aTmp(iCount)

  For iLoop = iLower to iCount
    iTmpUpper = iCount - iLoop

    ReDim Preserve aTmp(iTmpUpper)
    aTmp = split(strIndex, ",")

    iRnd = Int(Rnd * (iTmpUpper + 1))

    strNewIndex = strNewIndex & aArray(aTmp(iRnd)) & ","

    aTmp(iRnd) = aTmp(iTmpUpper)

    ReDim Preserve aTmp(iTmpUpper - 1)
    strIndex = join(aTmp, ",")


  strNewIndex = Left(strNewIndex, Len(strNewIndex) - 1)

  JumbleArray = split(strNewIndex, ",")
End Function

[Return to the Article] | [View the Quick 'n' Dirty Reordering Example] | [View the Recordset Reordering Demo]