Pro/Selection/RouletteBasic.pm untested

filter: Statementstmt 0.0% 0 / 40 Branchbran 0.0% 0 / 8 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 57 CC 5 SCAR 26.9
CC
5
Cov
0%
run
30.0
new
2.0
BEGIN
2.0
CRAP 14.7
1 package AI::Genetic::Pro::Selection::RouletteBasic;
2  
3 use warnings;
4 use strict;
5 use List::Util qw(min);
6 #use Data::Dumper; $Data::Dumper::Sortkeys = 1;
7 use List::MoreUtils qw(first_index);
8 use Carp 'croak';
9 #=======================================================================
10 sub new { bless \$_[0], $_[0]; }
11 #=======================================================================
12 sub run {
13 my ($self, $ga) = @_;
14
15 my ($fitness, $chromosomes) = ($ga->_fitness, $ga->chromosomes);
16 croak "You must set a number of parents to use the RouletteBasic strategy"
17 unless defined($ga->parents);
18 my $parents = $ga->parents;
19 my (@parents, @wheel);
20 my $const = min values %$fitness;
21 $const = $const < 0 ? abs($const) : 0;
22 my $total = 0;
23 #-------------------------------------------------------------------
24 foreach my $key (keys %$fitness){
25 $total += $fitness->{$key} + $const;
26 push @wheel, [ $key, $total ];
27 }
28
29 for(0..$#$chromosomes){
30 my @group;
31 for(1..$parents){
32 my $rand = rand($total);
33 my $idx = first_index { $_->[1] > $rand } @wheel;
34 if($idx == 0){ $idx = 1 }
35 elsif($idx == -1 ) { $idx = scalar @wheel; }
36 push @group, $wheel[$idx-1]->[0];
37 }
38 push @parents, pack 'I*', @group;
39 }
40
41 #-------------------------------------------------------------------
42 return \@parents;
43 }
44 #=======================================================================
45  
46 1;