How to randomize a sorted array?
Author Message
How to randomize a sorted array?

I am currently writing a program which strange as it may sound
requires a procedure to take a sorted array and to randomize it, that
is to shuffle an array much like a deck of cards.  It sounds like an
easy procedure to write but for some reason I can't get it, if any one
you can help or send me the code please e-mail me I'M DESPERATE!!

Thu, 17 Jun 1999 03:00:00 GMT
How to randomize a sorted array?

Quote:

> I am currently writing a program which strange as it may sound
> requires a procedure to take a sorted array and to randomize it, that
> is to shuffle an array much like a deck of cards.  It sounds like an
> easy procedure to write but for some reason I can't get it, if any one
> you can help or send me the code please e-mail me I'M DESPERATE!!

If you think of the array as a table, with items as rows, then you can
add a new column to the array, populate the column with random numbers
(use real numbers, not integers, so you have only a negligible chance of
any tied scores), and sort on the new column.  This works very nicely in
spreadsheets, where macro languages are a bother but global operations

Alternatively, you can use the standard algorithm to produce a random
permutation of a set of N items:

Set EndPoint=N
Loop: Pick a random number RN from 1 to EndPoint
Interchange Array[EndPoint] with Array[RN]
Decrement EndPoint by 1
If EndPoint>1, go back to Loop

Any array item, including Array[N], has an equal chance of winding up in
the Array[N] position.  Any remaining item has an equal chance of
winding up as Array[N-1], etc.  It can be mathematically proven that, if
your random number generator is good, then this generates all
permutations with equal probability (1/N!).

Howard Kaplan
Toronto, Ontario

Thu, 17 Jun 1999 03:00:00 GMT

 Page 1 of 1 [ 2 post ]

Relevant Pages