File Coverage

blib/lib/AI/Genetic/Pro/Mutation/Combination.pm
Criterion Covered Total %
statement 33 33 100.0
branch 7 8 87.5
condition 1 3 33.3
subroutine 6 6 100.0
pod 0 2 0.0
total 47 52 90.3


line stmt bran cond sub pod time code
1             package AI::Genetic::Pro::Mutation::Combination;
2              
3 1     1   6 use warnings;
  1         3  
  1         47  
4 1     1   9 use strict;
  1         2  
  1         47  
5 1     1   7 use List::MoreUtils qw(first_index);
  1         2  
  1         639  
6             #use Data::Dumper; $Data::Dumper::Sortkeys = 1;
7             #=======================================================================
8 1     1 0 9 sub new { bless \$_[0], $_[0]; }
9             #=======================================================================
10             sub run {
11 1     1 0 3 my ($self, $ga) = @_;
12              
13             # this is declared here just for speed
14 1         7 my $mutation = $ga->mutation;
15 1         5 my $chromosomes = $ga->chromosomes;
16 1         5 my $_translations = $ga->_translations;
17 1         8 my ($fitness, $_fitness) = ($ga->fitness, $ga->_fitness);
18 1         6 my $inv = $mutation / 2;
19            
20             # main loop
21 1         6 for my $idx (0..$#$chromosomes){
22            
23 1124         1492 my $rand = rand;
24            
25 1124 100       2728 if($rand < $inv) { tied(@{$chromosomes->[$idx]})->reverse; }
  26 100       736  
  26         99  
26             elsif($rand < $mutation){
27 22         25 my $el = int rand @{$chromosomes->[$idx]};
  22         107  
28 22         35 my $new = int rand @{$_translations->[0]};
  22         44  
29 22 100       123 next if $new == $chromosomes->[$idx]->[$el];
30            
31 20     88   88 my $id = first_index { $_ == $new } @{$chromosomes->[$idx]};
  88         106  
  20         249  
32 20 50 33     253 $chromosomes->[$idx]->[$id] = $chromosomes->[$idx]->[$el] if defined $id and $id != -1;
33 20         87 $chromosomes->[$idx]->[$el] = $new;
34             }
35            
36             # we need to change fitness
37 1122         3069 $_fitness->{$idx} = $fitness->($ga, $chromosomes->[$idx]);
38             }
39            
40 1         10 return 1;
41             }
42             #=======================================================================
43             1;