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

Re: [FWP] Perl Card Games



On Tue, Aug 03, 1999 at 01:43:48PM -0700, Eli Evans wrote:
> 
> 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.)

Interesting. 5.004 on linux yields:

fermi2:~>perl -e "print join ' ', sort {$a <=> (int rand 50)} (1..50)"
a: Undefined variable.

More interesting still, (using 26 numbers for easier readability than 50)

    fermi2:~>perl
    print (join(' ', sort {$a <=> (int rand $l)} (1..$l)),"\n\n");
    print (join(' ', sort {$a <=> (int rand $l)} (1..$l)),"\n");
    1 22 26 4 2 3 25 5 19 6 20 24 12 13 8 10 11 7 23 21 14 9 18 16 17 15

    1 2 3 7 4 26 8 6 14 5 9 25 24 23 15 11 13 10 12 21 17 22 19 16 20 18

I'm not sure whether you meant this by "does exactly what one might expect".
Because what it does is *not at all* randomize these integers. Notice the
"1 2 3" in the second example? When I tried it with 50, my first try had 
1..6 still consecutive, my second had 1..4.

Here's a more complete quotation from the sort docs:

    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.  This is entirely due to and dependent
    upon your system's qsort(3) library routine; this routine often avoids
    sanity checks in the interest of speed.

So it may depend on the qsort routine. But basically, it looks like the
early numbers (um, "cards") in the list don't ever get moved, presumably
because the routine keeps deciding to move things based on whether a random
number between 0 and 49 is greater than $a. When $a is 1, this happens very
rarely.


> 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.

Ouch. Oops. I perhaps meant "10*int(rand())-5". When I do this, I seem to
get things that aren't truly random. That is, it looks like the lower
numbers stay mostly, though not exclusively, on the lower end of the list. 
I assume again that that's dependent on the way qsort is done. 

-Amir

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