| 1 | #!/usr/local/bin/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 | ||
| 10 | get_pool_roulette_wheel get_pool_binary_tournament produce_offspring ); | ||
| 11 | use Sort::Key::Top qw(rnkeytop); | ||
| 12 | |||
| 13 | my $length = shift || 64; | ||
| 14 | my $number_of_strings = shift || 64; | ||
| 15 | my $number_of_generations = shift || 100; | ||
| 16 | my $pool = shift || "roulette"; | ||
| 17 | |||
| 18 | |||
| 19 | my @population; | ||
| 20 | my %fitness_of; | ||
| 21 | for (my $i = 0; $i < $number_of_strings; $i++) { | ||
| 22 | $population[$i] = random_chromosome( $length); | ||
| 23 | $fitness_of{$population[$i]} = max_ones( $population[$i] ); | ||
| 24 | } | ||
| 25 | |||
| 26 | my $get_pool; | ||
| 27 | if ( $pool eq "roulette" ) { | ||
| 28 | $get_pool = \&get_pool_roulette_wheel; | ||
| 29 | } else { | ||
| 30 | $get_pool = \&get_pool_binary_tournament; | ||
| 31 | } | ||
| 32 | my @best; | ||
| 33 | my $generations=0; | ||
| 34 | do { | ||
| 35 | my @pool = $get_pool->( \@population, \%fitness_of, $number_of_strings ); | ||
| 36 | my @new_pop = produce_offspring( \@pool, $number_of_strings/2 ); | ||
| 37 | for my $p ( @new_pop ) { | ||
| 38 | if ( !$fitness_of{$p} ) { | ||
| 39 | $fitness_of{$p} = max_ones( $p ); | ||
| 40 | } | ||
| 41 | } | ||
| 42 | @best = rnkeytop { $fitness_of{$_} } $number_of_strings/2 => @population; | ||
| 43 | @population = (@best, @new_pop); | ||
| 44 | print "Best so far $best[0] with fitness $fitness_of{$best[0]}\n"; | ||
| 45 | } while ( ( $generations++ < $number_of_generations ) and ($fitness_of{$best[0]} != $length )); | ||
| 46 | |||
| 47 | |||
| 48 | |||
| 49 | __END__ |