LinkBack Thread Tools Search this Thread Display Modes
Prev Previous Post   Next Post Next
  #5   Report Post  
Posted to microsoft.public.excel.programming
external usenet poster
 
Posts: 1
Default random permutation of an array

The following is a generalized shuffling routine that I have posted in the
past over in the compiled VB newsgroups, but it works fine in the VBA world
of Excel as well. Give it an array of elements and it will put them in
random order and return the randomized elements back in the original array
that was passed to it. It only visits *each* array element *once* so it is
quick. The code takes care of running the Randomize statement one time only
(which is all that is necessary).

Sub RandomizeArray(ArrayIn As Variant)
Dim X As Long
Dim RandomIndex As Long
Dim TempElement As Variant
Static RanBefore As Boolean
If Not RanBefore Then
RanBefore = True
Randomize
End If
If VarType(ArrayIn) = vbArray Then
For X = UBound(ArrayIn) To LBound(ArrayIn) Step -1
RandomIndex = Int((X - LBound(ArrayIn) + 1) * _
Rnd + LBound(ArrayIn))
TempElement = ArrayIn(RandomIndex)
ArrayIn(RandomIndex) = ArrayIn(X)
ArrayIn(X) = TempElement
Next
Else
'The passed argument was not an array
'Put error handler here, such as . . .
Beep
End If
End Sub

After passing your array into the RandomizeArray subroutine, its elements
will be randomly reordered. The passed array may be of any normal type --
integer, string, single, etc. The neat thing is, if you pass an already
randomized array to this routine, those randomly ordered elements will be
randomize -- sort of like shuffling an already shuffled deck of cards.

Rick


"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




 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules

Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Random Number Array Ken Hudson Excel Programming 1 June 14th 07 11:12 PM
Discrete random numbers into an array? festdaddy Excel Programming 4 August 21st 06 10:35 PM
permutation of values in 2 dimensional array [email protected] Excel Programming 1 August 21st 06 08:36 PM
random mumber array jedg Excel Programming 3 March 31st 06 03:43 PM
Creating a Combination or Permutation Array in Excel D.L. Excel Programming 4 November 1st 04 05:32 PM


All times are GMT +1. The time now is 04:52 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Copyright ©2004-2025 ExcelBanter.
The comments are property of their posters.
 

About Us

"It's about Microsoft Excel"