41 lines
1.1 KiB
Plaintext
41 lines
1.1 KiB
Plaintext
program weasel;
|
|
setrandom(0);
|
|
|
|
target := "METHINKS IT IS LIKE A WEASEL";
|
|
charset := {c : c in " ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
|
|
mutation_rate := 0.1;
|
|
generation_size := 100;
|
|
|
|
loop init
|
|
current := +/[random charset : c in target];
|
|
doing
|
|
print(lpad(str fitness(current, target), 3), current);
|
|
while current /= target do
|
|
current := next_generation(
|
|
current, target, mutation_rate, generation_size, charset);
|
|
end loop;
|
|
|
|
proc fitness(candidate, target);
|
|
return #[i : i in [1..#target] | candidate(i) /= target(i)];
|
|
end proc;
|
|
|
|
proc mutate(candidate, mutation_rate, charset);
|
|
return +/[
|
|
if random 1.0 < mutation_rate
|
|
then random charset
|
|
else c
|
|
end
|
|
: c in candidate
|
|
];
|
|
end proc;
|
|
|
|
proc next_generation(
|
|
parent, target, mutation_rate, generation_size, charset);
|
|
children := {
|
|
[fitness(c:=mutate(parent, mutation_rate, charset), target), c]
|
|
: i in [1..generation_size]
|
|
};
|
|
return random children{min/domain children};
|
|
end proc;
|
|
end program;
|