37 lines
1.1 KiB
Plaintext
37 lines
1.1 KiB
Plaintext
constant target = "METHINKS IT IS LIKE A WEASEL",
|
|
AZS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
|
|
C = 5000, -- children in each generation
|
|
P = 15 -- probability of mutation (1 in 15)
|
|
|
|
function fitness(string sample, string target)
|
|
return sum(sq_eq(sample,target))
|
|
end function
|
|
|
|
function mutate(string s, integer n)
|
|
for i=1 to length(s) do
|
|
if rand(n)=1 then
|
|
s[i] = AZS[rand(length(AZS))]
|
|
end if
|
|
end for
|
|
return s
|
|
end function
|
|
|
|
string parent = mutate(target,1) -- (mutate with 100% probability)
|
|
sequence samples = repeat(0,C)
|
|
integer gen = 0, best, fit, best_fit = fitness(parent,target)
|
|
while parent!=target do
|
|
printf(1,"Generation%3d: %s, fitness %3.2f%%\n", {gen, parent, (best_fit/length(target))*100})
|
|
best_fit = -1
|
|
for i=1 to C do
|
|
samples[i] = mutate(parent, P)
|
|
fit = fitness(samples[i], target)
|
|
if fit > best_fit then
|
|
best_fit = fit
|
|
best = i
|
|
end if
|
|
end for
|
|
parent = samples[best]
|
|
gen += 1
|
|
end while
|
|
printf(1,"Finally, \"%s\"\n",{parent})
|