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