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
4GuysFromRolla.com
ASPMessageboard.com
ASPFAQs.com

The Randomly Reordered Array Display
ASPFAQs.com
ASPMessageboard.com
4GuysFromRolla.com

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 & ","
  Next

  '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, ",")

  Next

  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]