View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Bernard Liengme Bernard Liengme is offline
external usenet poster
 
Posts: 4,393
Default random permutation of an array

With the array in A1:A10;
Select B1:B10 (or any suitable vertical range)
Use =RandomA(A1:A10); commit with CTRL+SHIFT+ENTER
-----------------------------
Option Base 1
Function randomA(myrange)
Dim myarray(100, 2)
rcount = myrange.Count
For j = 1 To rcount
myarray(j, 1) = myrange(j) 'transfer data from cell to array
myarray(j, 2) = Rnd 'give second vector a random value
Next j
For j = 1 To rcount - 1 'bubble sort by random number
For k = j To rcount
If myarray(k, 2) myarray(j, 2) Then
tempa = myarray(j, 1)
tempb = myarray(j, 2)
myarray(j, 1) = myarray(k, 1)
myarray(j, 2) = myarray(k, 2)
myarray(k, 1) = tempa
myarray(k, 2) = tempb
End If
Next k
Next j
randomA = myarray
End Function
-----------------------------------------

This uses a simple (inefficient but easy to code) sorting algorithm
best wishes
--
Bernard V Liengme
Microsoft Excel MVP
http://people.stfx.ca/bliengme
remove caps from email

"Shatin" wrote in message
...
Can anyone help me with a script that would shuffle the elements of an
array of integers randomly. For example:

MyArray before shuffling: 1, 2, 3, 4, 5
MyArray after shuffling: 3, 5, 4, 2, 1

I want the reordering to be really random.

TIA