#! /usr/bin/perl use strict; my ($thestring, $popsize, $str_len, @chr, $i, $str, @init_pop, @init_p +op_fitness, $max_fit); # GA To match the string: $thestring = "the quick brown dog jumped over the lazy fox"; # step one, create an inital population of strings the same size $popsize = 10; $str_len = length($thestring); # put list of valid characters into @chr @chr = qw(a b c d e f g h i j k l m n o p q r s t u v w x y z); @chr = (@chr, " "); my $best_match = 0; # fill each string with random character data for ($i = 0; $i < $popsize; $i++) { $str = join '', map $chr[rand @chr], 1..44; # store the string and it's fitness $init_pop[$i][0] = $str; $init_pop[$i][1] = fitness($str); # keep track of the best match for later if ($init_pop[$i][1] > $max_fit) { $best_match = $str; $max_fit = $init_pop[$i][1]; } } # now, sort the population by fitness (desc) # THIS DOESN'T WORK sort { $b->[1] <=> $a->[1] } @init_pop; for ($i = 0; $i < $popsize; $i++) { print ($init_pop[$i][1], "\n"); } # function to calculate the fitness of a given string, # that is how many characters match $thestring sub fitness { my $test_str = $_[0]; my ($j, $fit); $fit = 0; for ($j = 0; $j < $str_len; $j++) { if (substr($test_str, $j, 1) eq substr($thestring, $j, 1)) { + $fit++; } } return $fit; }
[download]