in reply to Shuffle an array

Basically the method works like this.

N is the number of items in the array.

Pick an element from 1 to N at random. Switch that element with the first element.

Now pick an element between 2 and N at random. Switch that element with the second element.

Then pick an element beween 3 and N at random. And switch that element with the third element.

Repeat those two step N-1 times and you have shuffled the array.

If that doesn't explain it for you, try getting a pack of card, put them in order and do the process manually.Even using cards 1 to 6 and a dice, and doing the process a couple of times should clarify things if my words don't help.

In Perl, the counting runs 0 to N-1 each time, but the logic remains the same.


Nah! You're thinking of Simon Templar, originally played (on UKTV) by Roger Moore and later by Ian Ogilvy

Replies are listed 'Best First'.
Re: Re: Shuffle an array
by FireBird34 (Pilgrim) on Nov 09, 2002 at 02:06 UTC
    Ah, ok. Make more sense now (yea, I got the N-1 stuff ;)). Didn't exactally know how the whole process worked. Thanks =)
Re: Re: Shuffle an array
by thinker (Parson) on Nov 09, 2002 at 10:54 UTC
    Hi BrowserUk,

    This doesn't give a fair shuffle. This is well documented, as it is in the FAQ, and is explained well in the Perl Cookbook. A recent node explains it. Check here.

    cheers

    thinker

      Are you saying my description is inaccurate? If so, please clarify in what way you think that it is wrong.

      My description is accurate. The link you give chooses a random value from 1 to n each time. My description reduces the range by 1 each time. This is the correct Fisher-Yates technique.


      Nah! You're thinking of Simon Templar, originally played (on UKTV) by Roger Moore and later by Ian Ogilvy