RosettaCodeData/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6

14 lines
451 B
Raku
Raw Permalink Normal View History

2013-04-10 22:43:41 -07:00
constant target = "METHINKS IT IS LIKE A WEASEL";
constant mutate_chance = .08;
2015-11-18 06:14:39 +00:00
constant @alphabet = flat 'A'..'Z',' ';
2013-04-10 22:43:41 -07:00
constant C = 100;
2017-09-23 10:01:46 +02:00
sub mutate { [~] (rand < mutate_chance ?? @alphabet.pick !! $_ for $^string.comb) }
2019-09-12 10:33:56 -07:00
sub fitness { [+] $^string.comb Zeq target.comb }
2013-04-10 22:43:41 -07:00
loop (
2015-11-18 06:14:39 +00:00
my $parent = @alphabet.roll(target.chars).join;
2013-04-10 22:43:41 -07:00
$parent ne target;
$parent = max :by(&fitness), mutate($parent) xx C
2015-02-20 00:35:01 -05:00
) { printf "%6d: '%s'\n", $++, $parent }