A couple of days ago, I had the need to quickly randomize the order of an array. I crafted the following snippet, based in a Schwartzian Transform...

@list = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, rand +] } @list;

Replies are listed 'Best First'.
Re: Schwartzian transform for randomizing a list
by Aristotle (Chancellor) on Jan 02, 2004 at 14:03 UTC
    use List::Util qw(shuffle); @list = shuffle @list;

    Makeshifts last the longest.

Re: Schwartzian transform for randomizing a list
by RMGir (Prior) on Jan 02, 2004 at 18:08 UTC
    Hehe, that'll work.

    You might want to look at Fisher-Yates theory for the theory behind a slightly "better" way to do it, but I'm sure your answer did the job well enough for what you needed.

    F-Y is going to be a lot better if you have to do a lot of shuffles, or if you're shuffling large lists, though. It's cheaper than a sort (O(n) vs O(n lg n), I believe).


    Mike
Re: Schwartzian transform for randomizing a list
by fokat (Deacon) on Jan 02, 2004 at 18:41 UTC

    Thanks to Aristotle (++) and RMGir (++). I'll take a look at both of your answers.

    Best regards

    -lem, but some call me fokat