| 1 | package AI::Genetic::Pro::Crossover::PointsAdvanced; | ||
| 2 | |||
| 3 | use warnings; | ||
| 4 | use strict; | ||
| 5 | use List::MoreUtils qw(first_index); | ||
| 6 | #use Data::Dumper; $Data::Dumper::Sortkeys = 1; | ||
| 7 | #use AI::Genetic::Pro::Array::PackTemplate; | ||
| 8 | #======================================================================= | ||
| 9 | sub new { bless { points => $_[1] ? $_[1] : 1 }, $_[0]; } | ||
| 10 | #======================================================================= | ||
| 11 | sub run { | ||
| 12 | my ($self, $ga) = @_; | ||
| 13 | |||
| 14 | my ($chromosomes, $parents, $crossover) = ($ga->chromosomes, $ga->_parents, $ga->crossover); | ||
| 15 | my ($fitness, $_fitness) = ($ga->fitness, $ga->_fitness); | ||
| 16 | #------------------------------------------------------------------- | ||
| 17 | while(my $elders = shift @$parents){ | ||
| 18 | my @elders = unpack 'I*', $elders; | ||
| 19 | |||
| 20 | unless(scalar @elders){ | ||
| 21 | push @$chromosomes, $chromosomes->[$elders[0]]; | ||
| 22 | next; | ||
| 23 | } | ||
| 24 | |||
| 25 | my ($min, $max) = (0, $#{$chromosomes->[0]} - 1); | ||
| 26 | if($ga->variable_length){ | ||
| 27 | for my $el(@elders){ | ||
| 28 | my $idx = first_index { $_ } @{$chromosomes->[$el]}; | ||
| 29 | $min = $idx if $idx > $min; | ||
| 30 | $max = $#{$chromosomes->[$el]} if $#{$chromosomes->[$el]} < $max; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | my @points; | ||
| 35 | if($min < $max and $max - $min > 2){ | ||
| 36 | my $range = $max - $min; | ||
| 37 | @points = map { $min + int(rand $range) } 1..$self->{points}; | ||
| 38 | } | ||
| 39 | |||
| 40 | @elders = map { $chromosomes->[$_]->clone } @elders; | ||
| 41 | for my $pt(@points){ | ||
| 42 | @elders = sort { | ||
| 43 | splice @$b, 0, $pt, splice( @$a, 0, $pt, @$b[0..$pt-1] ); | ||
| 44 | 0; | ||
| 45 | } @elders; | ||
| 46 | } | ||
| 47 | |||
| 48 | push @$chromosomes, @elders; | ||
| 49 | } | ||
| 50 | #------------------------------------------------------------------- | ||
| 51 | # wybieranie potomkow ze zbioru starych i nowych osobnikow | ||
| 52 | @$chromosomes = sort { $fitness->($ga, $a) <=> $fitness->($ga, $b) } @$chromosomes; | ||
| 53 | splice @$chromosomes, 0, scalar(@$chromosomes) - $ga->population; | ||
| 54 | %$_fitness = map { $_ => $fitness->($ga, $chromosomes->[$_]) } 0..$#$chromosomes; | ||
| 55 | #------------------------------------------------------------------- | ||
| 56 | return $chromosomes; | ||
| 57 | } | ||
| 58 | #======================================================================= | ||
| 59 | 1; |