Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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]
[LanX]: interesting the author doesn't seem to accept javascript as a scripting language
[LanX]: ... and calls php7 the winner oO
[RonW]: RPerl is only a curiosity to me. I can see where some one who primarily codes in Perl might find RPerl useful, but to me, given the choice between RPerl's restrictions and C, I'd choose C
[LanX]: Rperl had better chances as alternative for inline::cpp

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2017-05-22 20:40 GMT
Find Nodes?
    Voting Booth?