sub mutate{ my @string = @{$_[0]}; for my $i (0.. $#string){ my $aref = $string[$i]; #print "\n"; if (rand() < $mutation_rate){ my $position1 = int(rand($#{$aref})); my $position2 = int(rand($#{$aref})); if ($position1 ne $position2){ my $temp = $string[$i][$position1]; $string[$i][$position1] = $string[$i][$position2]; $string[$i][$position2] = $temp; } } } return \@string; }
You have an off-by-one error. If @$aref contains 10 elements it will have the indices 0 to 9 and int(rand($#{$aref})) will only pick a number in the range 0 to 8.
Also, perl has a more efficient idiom for swapping values:
sub mutate{ my @string = @{ $_[ 0 ] }; for my $i ( 0 .. $#string ){ my $aref = $string[ $i ]; #print "\n"; if ( rand() < $mutation_rate ){ my $position1 = int rand @$aref; my $position2 = int rand @$aref; if ( $position1 != $position2 ){ @{ $string[ $i ] }[ $position1, $position2 ] = @{ $str +ing[ $i ] }[ $position2, $position1 ]; } } } return \@string; }
Update: Also you used the wrong comparison operator. Changed ne to !=.
In reply to Re: Problem of referencing into subroutines.
by jwkrahn
in thread Problem of referencing into subroutines.
by zli034
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |