in reply to Re: unsorted list
in thread unsorted list

As far as I can tell, your code is a "recoding" of the Fisher-Yates shuffle:
sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } }

And permuting your version:

for (0..($#arr-1)) { $n = int (rand() * ($#arr - $_ + 1)) + $_; $t = $arr[$n]; $arr[$n] = $arr[$_]; $arr[$_] = $t; }

for (0..($#arr-1)) { $n = int (rand() * ($#arr - $_ + 1)) + $_;
$t = $arr[$n]; $arr[$n] = $arr[$_]; $arr[$_] = $t;
}

for (0..($#arr-1)) { $n = int (rand() * ($#arr - $_ + 1)) + $_;
@$arr[$_,$n] = @$arr[$n,$_];
}

for (0..($#arr-1)) { $n = int (rand() * ($#arr - $_ + 1)) + $_;
# next if $_ == $n;
@$arr[$_,$n] = @$arr[$n,$_]; }

The remaining two lines are functionally equivalent:

for (0..($#arr-1)) { # Your Version $n = int (rand() * ($#arr - $_ + 1)) + $_; for ($i = @$array; --$i; ) { # Fisher-Yates my $j = int rand ($i+1);

Frankly, I prefer your formulation (with the addition of the next if line) as it doesn't use an incomplete for loop, but the codes are equivalent.

UPDATE: For the benefit of the astute who realized that the remaining two lines weren't entirely equivalent:

for (0..($#arr-1)) { $n = int (
rand() * ($#arr - $_ + 1)
) + $_; # next if $_ == $n; @$arr[$_,$n] = @$arr[$n,$_]; }

for (0..($#arr-1)) { $n = int (
rand($#arr - $_ + 1)
) + $_; # next if $_ == $n; @$arr[$_,$n] = @$arr[$n,$_]; }

for (0..($#arr-1)) { $n = int (rand($#arr - $_ + 1))
+ $_
; # next if $_ == $n; @$arr[$_,$n] = @$arr[$n,$_]; }

Fisher-Yates traverses down the array, whereas this version traverses up the array (due to the appended + $_). Remove the addition and the codes are equivalent; leave it in and the codes are functionally equivalent.