On Wed, Jul 25, 2001 at 07:02:11PM -0500, Craig S.Cottingham wrote:
>
> > I guess the questions are: 1. why doesn't this work? and 2. can it be
> > made to work?
>
> 2. Yes, sort of.
>
> #!/usr/bin/perl -w
>
> use strict;
>
> my @list = (1, 4, 2, 8, 5, 7, 3, 6, 0, 9);
>
> my @sorted = sort { $a <=> $b } @list;
>
> for (1..@list) {
> my @dummy = sort {
> ($a,$b) = ($b,$a) if (($a <=> $b) > 0);
> 0;
> } @list;
> }
>
> local $, = ', ';
> print "Original: @list\n";
> print "Sorted: @sorted\n";
I believe that it produced the right results on the inputs you tested
it with. But can you proof your trick will always sort the array?
> Hmm. Shuffling the contents of a list?
>
> #!/usr/bin/perl -w
>
> use strict;
>
> my @list = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
> local $, = ', ';
> print "Original: @list\n";
>
> for (1..6) {
> my @dummy = sort {
> ($a,$b) = ($b,$a) if ((rand(2) - 1) < 0);
> 0;
> } @list;
> }
>
> print "Shuffled: @list\n";
I doubt very much that this is a fair shuffle. See, for a fair shuffle
each of the @list! possible permutations should have the same chance
of resulting. And, under the assumption 'rand' is perfect', I don't see
your shuffle doing that.
Abigail