| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use lib qw( ../lib lib ); | ||
| 7 | |||
| 8 | use version; our $VERSION = qv('0.0.3'); | ||
| 9 | use Algorithm::Evolutionary::Simple qw( random_chromosome max_ones_fast | ||
| 10 | single_generation); | ||
| 11 | use Sort::Key::Top qw(rnkeytop); | ||
| 12 | |||
| 13 | my $length = shift || 64; | ||
| 14 | my $number_of_strings = shift || 64; | ||
| 15 | |||
| 16 | my @population; | ||
| 17 | my %fitness_of; | ||
| 18 | my $total_fitness; | ||
| 19 | for (my $i = 0; $i < $number_of_strings; $i++) { | ||
| 20 | $population[$i] = random_chromosome( $length); | ||
| 21 | $fitness_of{$population[$i]} = max_ones_fast( $population[$i] ); | ||
| 22 | $total_fitness += $fitness_of{$population[$i]}; | ||
| 23 | } | ||
| 24 | |||
| 25 | my $evaluations=$#population+1; | ||
| 26 | |||
| 27 | do { | ||
| 28 | @population = single_generation( \@population, \%fitness_of, $total_fitness ); | ||
| 29 | $total_fitness = 0; | ||
| 30 | for my $p ( @population ) { | ||
| 31 | if ( !$fitness_of{$p} ) { | ||
| 32 | $fitness_of{$p} = max_ones_fast( $p ); | ||
| 33 | } | ||
| 34 | $total_fitness += $fitness_of{$p}; | ||
| 35 | } | ||
| 36 | $evaluations += $#population -1; # Two are kept from previous generation | ||
| 37 | print "Best so far $population[0] with fitness $fitness_of{$population[0]} and evaluated $evaluations\n"; | ||
| 38 | } while ($fitness_of{$population[0]} != $length ); | ||
| 39 | |||
| 40 | |||
| 41 | |||
| 42 | __END__ |