in reply to Re: help in understanding the standard array shuffle
in thread help in understanding the standard array shuffle

See update...ugh A nit perhaps, but...:

It would seem this shuffle guarantees that no element remains in it's current position. This seems less than random.

@array= sort { (-1,0,1)[int rand 3]} @array
I suspect you never see this type of thing because of the inefficiency. The cookbook example is making length(@foo) or less comparisons, the random sort is potentially doing more than length(@foo) comparisons.

Update: Hmm...my first statement, after further thought, appears to be silly.

  • Comment on Re: Re: help in understanding the standard array shuffle

Replies are listed 'Best First'.
Re: Re: Re: help in understanding the standard array shuffle
by extremely (Priest) on Feb 14, 2001 at 19:26 UTC
    You are incorrect, the routine leaves open the possibility of keeping an item in place. Note the line next if ... there. In fact, as I recall it, that shuffle can be shown to have an even chance of producing any permutation with a true random source and is pretty damn good even with a really BAD random source.

    Also, the rand trick you employ can exit early and leave chunks untouched. sortrather relies on consistency, if b>a and c>b then c>a should be implied. If I read the sort code right, violating that could lead to serious goofs like potentially never ending and such.

    --
    $you = new YOU;
    honk() if $you->love(perl)

      All valid comments, but my reply wasn't to the original node, it was to Gloom's node, which was suggesting @array = sort { (-1,1)[int rand 2] } @array;.

      In any case, I was nitting on the lack of a 0 return, which in light of your comments, matters little. (since random results from a sort sub are bad news...)

        Sorry, and of course merlyn said it better at the right depth. =) (You are right tho, to get the evil way correct, adding 0 to the mix would be necessary...)

        --
        $you = new YOU;
        honk() if $you->love(perl)

Re: Re: Re: help in understanding the standard array shuffle
by arhuman (Vicar) on Feb 14, 2001 at 19:21 UTC
    It would seem this shuffle guarantees that no element remains in it's current position. This seems less than random.

    My tests show that SOME elements stay in place !
    Did I miss something ?

    Note: I suspect however that the distribution is not perfect(the items "don't move too far from their position" so i suspect the "distribution" to be biased)...

    Anyway it's ok for me the way it is, just have to remember it's not a true 'statistical random' change...