Sunday, October 25, 2009

Randomly Reordering an Array

Randomly Reordering an Array,One quick and dirty way to do this is to
step through the array one element at a time, randomly picking a
number betweenthe upper and lower bounds of the array, and swap the
value of the element of the array at the current position with the
element of the array at the position of the randomly selected number.

<%
'****************************************
' This function randomly reorders the
' array aArray using a quick and dirty
' approach... It's fast!
'****************************************
Function ReOrderArrayQuickNDirty(ByVal aArray)

Dim iUpper, iLower, iLoop, iSwapPos, varTmp
iUpper = UBound(aArray)
iLower = LBound(aArray)

Randomize Timer

'Loop through the array, randomly swapping values
For iLoop = iLower to iUpper
'Get an array index to swap
iSwapPos = Int(Rnd * (iUpper + 1))

'Swap the current element with the element at iSwapPos
varTmp = aArray(iLoop)
aArray(iLoop) = aArray(iSwapPos)
aArray(iSwapPos) = varTmp
Next

ReOrderArrayQuickNDirty = aArray 'Return the jumbled array
End Function

Dim aSites
ReDim aSites(2)

aSites(0) = "4GuysFromRolla.com"
aSites(1) = "ASPMessageboard.com"
aSites(2) = "ASPFAQs.com"

'Display the array in-order
Dim iLoop
For iLoop = LBound(aSites) to UBound(aSites)
Response.Write aSites(iLoop) & "<BR>"
Next
response.write "<P>"

'Jumble up the array and display the new, random order!
aSites = ReOrderArrayQuickNDirty(aSites)
For iLoop = LBound(aSites) to UBound(aSites)
Response.Write aSites(iLoop) & "<BR>"
Next
%>


http://www.4guysfromrolla.com/webtech/110800-1.shtml

No comments:

Adobe News