my $gene_length = gene_length();
####
sub gene_length {
my @gls = ();
foreach my $key ( keys(%genome) ) {
push( @gls, length($key) );
}
@gls = sort(@gls);
if ( $gls[0] != $gls[$#gls] ) {
die("Invalid genotype");
}
return ( $gls[0] );
}
##
##
sub gene_length {
my $len = length( each %genome );
while( my $key = each %genome ) {
die "Invalid genotype" unless length( $key ) == $len;
}
return $len;
}
##
##
my %genome = (
'0001' => '1', '0010' => '2', '0011' => '3', '0100' => '4', '0101' => '5',
'0110' => '6', '0111' => '7', '1000' => '8', '1001' => '9',
'1010' => '+', '1011' => '-', '1100' => '*', '1101' => '/'
);
my $gene_length = gene_length();
##
##
sub get_nonrandom_chromosome {
### get_population_fitness_score() ###
### calculates the score for every chromosome ###
my $population_fitness_score = get_population_fitness_score();
my $rulet_position = rand($population_fitness_score);
my $temp_score = 0;
my $nonrandom_chromosome;
foreach my $chromosome (@population) {
### you then REcalculate them individually here ###
$temp_score += get_fitness_score($chromosome);
if ( $temp_score > $rulet_position ) {
$nonrandom_chromosome = $chromosome;
last;
}
}
return ($nonrandom_chromosome);
}
##
##
sub get_nonrandom_chromosome {
my @scores = map { get_fitness_score($_) } @population;
my $rulet_position = rand( sum @scores );
my $temp_score = 0;
foreach my $i ( 0 .. $#scores ) {
$temp_score += $scores[ $i ];
return $population[ $i ] if $temp_score > $rulet_position;
}
}
##
##
my %memo;
sub get_result {
return $memo{ $_[0] } //= evalExpr( get_phenotype( $_[0], $gene_length ) );
}
##
##
sub evalExpr {
local $_ = shift;
s[(?<=[^*/+-])([*/+-])][<$1>]g;
1 while s[([^>]+)<([*/])>([^<]+)][$2 eq '*' ? $1 * $3 : $1 / $3]e;
1 while s[([^>]+)<([+-])>([^<]+)][$2 eq '+' ? $1 + $3 : $1 - $3]e;
return $_;
}