| 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; |