RosettaCodeData/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx

34 lines
2.5 KiB
Rexx
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
/*REXX program demonstrates an evolutionary algorithm (by using mutation). */
parse arg children MR seed . /*get optional arguments from the C.L. */
if children=='' then children = 10 /*# children produced each generation. */
if MR =='' then MR = "4%" /*the character Mutation Rate each gen.*/
if right(MR,1)=='%' then MR=strip(MR,,"%")/100 /*expressed as a percent? Then adjust.*/
if seed\=='' then call random ,,seed /*SEED allow the runs to be repeatable.*/
2015-11-18 06:14:39 +00:00
abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; Labc=length(abc)
target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar=length(target)
2016-12-05 22:15:40 +01:00
parent= mutate( left('',Ltar), 1) /*gen rand string,same length as target*/
say center('target string', Ltar, "") 'children' "mutationRate"
say target center(children,8) center((MR*100/1)'%', 12); say
say center('new string' ,Ltar, "") "closeness" 'generation'
2013-04-10 16:57:12 -07:00
2016-12-05 22:15:40 +01:00
do gen=0 until parent==target; close=fitness(parent)
2013-06-05 21:47:54 +00:00
almost=parent
2016-12-05 22:15:40 +01:00
do children; child=mutate(parent,MR)
_=fitness(child); if _<=close then iterate
close=_; almost=child
say almost right(close, 9) right(gen,10)
end /*children*/
2013-06-05 21:47:54 +00:00
parent=almost
end /*gen*/
2016-12-05 22:15:40 +01:00
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fitness: parse arg x; $=0; do k=1 for Ltar; $=$+(substr(x,k,1)==substr(target,k,1)); end
2015-11-18 06:14:39 +00:00
return $
2016-12-05 22:15:40 +01:00
/*──────────────────────────────────────────────────────────────────────────────────────*/
mutate: parse arg x,rate; $= /*set X to 1st argument, RATE to 2nd.*/
2017-09-23 10:01:46 +02:00
do j=1 for Ltar; r=random(1,100000) /*REXX's max for RANDOM*/
2016-12-05 22:15:40 +01:00
if .00001*r<=rate then $=$ || substr(abc,r//Labc+1, 1)
else $=$ || substr(x ,j , 1)
2015-11-18 06:14:39 +00:00
end /*j*/
return $