28 lines
836 B
Plaintext
28 lines
836 B
Plaintext
function evolve(parent,target,mutation_rate,num_children)
|
|
println("Initial parent is $parent, its fitness is $(fitness(parent,target))")
|
|
gens=0
|
|
while parent!=target
|
|
children=[mutate(parent,mutation_rate) for i=1:num_children]
|
|
bestfit,best=findmax(map(child->fitness(child,target),children))
|
|
parent=children[best]
|
|
gens+=1
|
|
if gens%10==0
|
|
println("After $gens generations, the new parent is $parent and its fitness is $(fitness(parent,target))")
|
|
end
|
|
end
|
|
println("After $gens generations, the parent evolved into the target $target")
|
|
end
|
|
|
|
fitness(s1,s2)=count(x->x,convert(Array{Char,1},s1).==convert(Array{Char,1},s2))
|
|
|
|
function mutate(s,rate)
|
|
new_s=""
|
|
for c in s
|
|
new_s*=string(rand()<rate?
|
|
" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[rand(1:27)]:c)
|
|
end
|
|
return new_s
|
|
end
|
|
|
|
evolve("IU RFSGJABGOLYWF XSMFXNIABKT","METHINKS IT IS LIKE A WEASEL",0.08998,100)
|