RNDArray




' Shuffle the elements of an array of any type

' (it doesn't work with arrays of objects or UDT)


Sub ArrayShuffle(arr As Variant)
Dim index As Long
Dim newIndex As Long
Dim firstIndex As Long
Dim itemCount As Long
Dim tmpValue As Variant

firstIndex = LBound(arr)
itemCount = UBound(arr) - LBound(arr) + 1

For index = UBound(arr) To LBound(arr) + 1 Step -1
' evaluate a random index from LBound to INDEX

newIndex = firstIndex + Int(Rnd * itemCount)
' swap the two items

tmpValue = arr(index)
arr(index) = arr(newIndex)
arr(newIndex) = tmpValue
' prepare for next iteration

itemCount = itemCount - 1
Next

End Sub










( rndarray.html )- by Paolo Puglisi - Modifica del 17/12/2023