in reply to Array Shuffler

(Please learn to use <code> tags around your code.)

The Fisher-Yates shuffle is usually written like this:

Update: No, actually it isn't as Dominus points out below. See many other posts in this thread for the correct implementation. I've left my version here as a reminder to myself not to re-invent well-known algorithms on he fly :(

foreach (0 .. $#array) { my $i = rand @arr; next if $i == $_; @array[$_, $i] = @array[$i, $_]; }
--
<http://www.dave.org.uk>

"Perl makes the fun jobs fun
and the boring jobs bearable" - me

Replies are listed 'Best First'.
Re: Re: Array Shuffler
by Dominus (Parson) on Jan 09, 2001 at 19:01 UTC
    Says davorg:
    The Fisher-Yates shuffle is usually written like this:
    No, the Fisher-Yates shuffle is only written that way by people who don't understand what they're doing.

    See the discussion on page 122 of Perl Cookbook for why.