[Chicago-talk] Random first numbers

Dean Serenevy dean at serenevy.net
Mon May 17 16:19:16 PDT 2010


On 05/17/2010 05:25 PM, Alan Mead wrote:
> #----------------------------------------------------------
> # Durstenfeld's implementation of Fisher and Yates
> #----------------------------------------------------------
> sub shuffle {
>  my $n = scalar @_;
>  while ( $n > 0 ) {
>    $n--;
>    my $j = int rand $n;
>    ($_[$j], $_[$n]) = ($_[$n], $_[$j]); # swap
>  }
> }
> 
> Assuming that shuffle() is not the culprit, I think it's just that when

Bad assumption. That is not the Fisher-Yates shuffle. Try this (from perlfaq):

sub shuffle {
  my $n = @_;
  while (--$n) {
    my $j = int rand ($n+1);
    @_[$n,$j] = @_[$j,$n];
  }
}

Note that:
* a no-op is possible in this version ($n may equal $j)
* The last $n through the loop is 1 not 0

Good Day,
  Dean


More information about the Chicago-talk mailing list