Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Schwartzian transform for randomizing a list

by fokat (Deacon)
on Jan 02, 2004 at 12:58 UTC ( [id://318302]=CUFP: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://318302]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-23 19:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found