[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

RE: [FWP] Perl Card Games



Amir said:
: I had the severely evil idea of:
: 
: @shuffled = sort {rand - .5} @shuffled;
: 
: But the sort docs say:
: 
:     The comparison function is required to behave.  If it returns
:     inconsistent results (sometimes saying $x[1] is less than $x[2] and
:     sometimes saying the opposite, for example) the Perl interpreter will
:     probably crash and dump core.
: 
: I guess dumping core doesn't usually qualify as FWP.

Well ... perldoc tells me that:

            The comparison function is required to behave. If it
            returns inconsistent results (sometimes saying `$x[1]'
            is less than `$x[2]' and sometimes saying the opposite,
            for example) the results are not well-defined.
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Further, not that I'm recommending it (in light of the docs, not because
it's not fun), but

    perl -e "print join ' ', sort {$a <=> (int rand 50)} (1..50)";

does exactly what one might expect. For me, anyway. (5.005_02 built for
MSWin32-x86-object.)

And further still,

    perl -e "print join ' ', sort {rand() - .5} (1..10)";

always results in '1 2 3 4 5 6 7 8 9 10'. According to the docs:

           If SUBNAME is specified, it gives the name of a subroutine that
           returns an integer less than, equal to, or greater than `0',
                      ^^^^^^^
           depending on how the elements of the array are to be ordered.

So, my guess is that since

    int(rand() - .5)

is always 0, no sorting would happen.

Regards,
________________________
Eli Evans
Text Preparation Manager
Libronix Corp.
mailto:eli@libronix.com
http://www.libronix.com
Ec 12:12; Jn 21:22



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe