Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re^2: Random array sorting

by bsoisoi
on Dec 05, 2007 at 17:35 UTC ( #655140=note: print w/replies, xml ) Need Help??

in reply to •Re: Random array sorting
in thread Random array sorting

I have an even easier way.
my @array = ('one', 'two', 4, 5, 23242, 'all the candy in the universe', 'zebras');
print $_, "\n" foreach (sort {int(rand(3))-1} @array);
Just makeup the -1, 0, 1 digits that $a cmp $b would return.

Replies are listed 'Best First'.
Re^3: Random array sorting
by merlyn (Sage) on Dec 05, 2007 at 18:31 UTC
    That's been shown time and time again to not be a "fair" shuffle, and in earlier Perl versions, would actually lose data or even core-dump. Bad. And yeah, I tried it in order to find that out.
Re^3: Random array sorting
by ikegami (Pope) on Dec 05, 2007 at 18:41 UTC

    Ignoring that it doesn't work, I don't see how

    print $_, "\n" foreach (sort {int(rand(3))-1} @array);

    is easier than

    print $_, "\n" foreach shuffle @array;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://655140]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-03-19 05:25 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (232 votes). Check out past polls.