Evolutionary algorithm: Difference between revisions

Added Easylang
m (Updated description and link for Fōrmulæ solution)
(Added Easylang)
 
(47 intermediate revisions by 24 users not shown)
Line 41:
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V target = Array(‘METHINKS IT IS LIKE A WEASEL’)
V alphabet = ‘ ABCDEFGHIJLKLMNOPQRSTUVWXYZ’
V p = 0.05
V c = 100
 
F neg_fitness(trial)
R sum(zip(trial, :target).map((t, h) -> Int(t != h)))
 
F mutate(parent)
R parent.map(ch -> (I random:() < :p {random:choice(:alphabet)} E ch))
 
V parent = (0 .< target.len).map(_ -> random:choice(:alphabet))
V i = 0
print((‘#3’.format(i))‘ ’parent.join(‘’))
L parent != target
V copies = ((0 .< c).map(_ -> mutate(:parent)))
parent = min(copies, key' x -> neg_fitness(x))
print((‘#3’.format(i))‘ ’parent.join(‘’))
i++</syntaxhighlight>
 
{{out}}
<pre>
0 FGUQJPIPMOUSPW MRHJQMNLF GZP
0 FGURJPIPMOUSPW LRHJQMSLF GZP
1 FGURJPIPMOUSPW LRHJQASLF GLP
2 FGURJPIPMOUSPW LRHJQASWFYGLP
3 FGURZPKZMOUSPW LRHJQASWFYGLP
4 FJUHZPKZMOUSPW LRHJQASWFYGLP
5 FJUHZNKZMOUSPW LRHJQASWFYGLP
6 FJUHZNKZMOUSPW LRHJBASWFYGLP
7 FJUHZNKSMOUSPW LRHJBASWFYGLP
8 FJUHKNKSMOU PW LRHJBABWFYGLP
9 FJUHKNKSMOU PW LRHJBABWFYGLL
10 FJUHKNKSMOU PW LRKJBABWFYGLL
...
76 METHINKS IT IS LIKE A WEASEL
</pre>
 
=={{header|8080 Assembly}}==
 
<langsyntaxhighlight lang="8080asm">MRATE: equ 26 ; Chance of mutation (MRATE/256)
COPIES: equ 100 ; Amount of copies to make
fname1: equ 5Dh ; First filename on command line (used for RNG seed)
Line 205 ⟶ 246:
maxptr: ds 2 ; Pointer to copy with best fitness
parent: equ $ ; Store current parent here
kids: equ $+tgtsz ; Store mutated copies here</langsyntaxhighlight>
 
{{out}}
Line 234 ⟶ 275:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm"> bits 16
cpu 8086
MRATE: equ 26 ; Mutation rate (MRATE/256)
Line 356 ⟶ 397:
rnddat: resb 4 ; RNG state
parent: resb target.size ; Place to store current parent
kids: resb COPIES*target.size ; Place to store children</langsyntaxhighlight>
 
{{out}}
Line 385 ⟶ 426:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
\ RosettaCode challenge http://rosettacode.org/wiki/Evolutionary_algorithm
\ Responding to the criticism that the implementation was too directed, this
Line 479 ⟶ 520:
"METHINKS IT IS LIKE A WEASEL"
setup-random initial-string evolve bye</langsyntaxhighlight>
 
The output:
Line 496 ⟶ 537:
Very simple fitness determination. For testing purposes you can add a static seed value to the RNG initializations (sample output uses '12345' for both).
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Numerics.Float_Random;
Line 619 ⟶ 660:
-- evolve!
Evolve;
end Evolution;</langsyntaxhighlight>
 
sample output:
Line 644 ⟶ 685:
380: METHINKS ITBIS LIKE A WEASEL, fitness: 27
Final ( 384): METHINKS IT IS LIKE A WEASEL, fitness: 28</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">PUT "ABCDEFGHIJKLMNOPQRSTUVWXYZ " IN alphabet
 
HOW TO RETURN initial.state target:
SHARE alphabet
PUT "" IN state
FOR c IN target: PUT state^choice alphabet IN state
RETURN state
 
HOW TO RETURN state fitness target:
PUT #target IN score
FOR i IN {1..#target}:
IF state item i = target item i: PUT score-1 IN score
RETURN score
 
HOW TO RETURN chance mutate state:
SHARE alphabet
PUT "" IN mutated
FOR i IN {1..#state}:
SELECT:
random < chance: PUT choice alphabet IN next
ELSE: PUT state item i IN next
PUT mutated^next IN mutated
RETURN mutated
 
HOW TO EVOLVE TOWARD target:
PUT 0.1 IN mutation.rate
PUT 100 IN generation.size
PUT initial.state target IN state
WHILE state fitness target > 0:
WRITE (state fitness target)>>2, ": ", state/
PUT {} IN next.generation
FOR i IN {1..generation.size}:
PUT mutation.rate mutate state IN child
PUT child fitness target IN score
PUT child IN next.generation[score]
PUT next.generation[min keys next.generation] IN state
WRITE (state fitness target)>>2, ": ", state/
 
EVOLVE TOWARD "METHINKS IT IS LIKE A WEASEL"</syntaxhighlight>
{{out}}
<pre>27: CYPPYRQHMACPLQIZLPETRJVVPYLI
26: CYPPYRQHMICPLQIZLPEDRJVVPILI
25: CYKPYRQH ICPLWIZLPEDRJVJPILI
24: CWKPWWQH ICPLSIZLPEDRJVJPILI
23: CWKPWWQH ICPLSIZLPEDR BJPILI
21: CWKPWWQH ICPLSIZLSEDA BJA LI
20: JWKPWWKH ICPLSIZLSEDA BJA LK
19: WWKPIWKG ICPLSIZLSEDA BJA LK
18: WWKPIWKG ICPLSILLSEDA BJA LK
17: WWKPIWKG ICPLSILISEDA BJA LK
17: IWMPIWKG ICPLSILISEDA BJA LK
16: IWMPIWKG ICPLSILISEDA WJA LK
15: IWMPIWKG ICPLSILISEDA WEA LK
...
1: METHINKS IT IS LIKE A WEAS L
1: METHINKS IT IS LIKE A WEAS L
1: METHINKS IT IS LIKE A WEAS L
0: METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|Aime}}==
{{trans|C}}
<langsyntaxhighlight lang="aime">integer
fitness(data t, data b)
{
Line 714 ⟶ 815:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>23 EAAXIZJROVOHSKREBNSAFHEKF B
Line 747 ⟶ 848:
 
=={{header|ALGOL 68}}==
{{trans|C|but using a fixed mutation rate}} Note: This specimen retains the original [[#C|C]] coding style.
{{works with|ALGOL 68|Revision 1 - no extensions to language used.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<syntaxhighlight lang="algol68">
<lang algol68>STRING target := "METHINKS IT IS LIKE A WEASEL";
STRING target := "METHINKS IT IS LIKE A WEASEL";
PROC fitness = (STRING tstrg)REAL:
Line 787 ⟶ 889:
INT iters := 0;
kid[LWB kid] := LOC[UPB target]CHAR;
REAL mutate rate = 0.05;
# initialize #
Line 795 ⟶ 897:
 
fits := fitness(parent);
WHILE fits < 100.0 DO
INT j;
REAL kf;
mutate rate := 1.0 - exp(- (100.0 - fits)/400.0);
FOR j FROM LWB kid TO UPB kid DO
mutate(kid[j], parent, mutate rate)
Line 809 ⟶ 910:
FI
OD;
IFfits iters MOD< 100 = .0 THEN
DO
kewe( parent, iters, fits, mutate rate )
kewe( parent, iters, fits, mutate rate );
FI;
iters+:=1
OD;
Line 820 ⟶ 921:
(
evolve
)
)</lang>
</syntaxhighlight>
Sample output:
<pre>
#0000 fitness: 0.00% 0.22120500 'JUQBKWCHNPJQBDVGDQUELSIJULMHYUGD LO LFDKHDJJNQIFQMPYMUX'
#01000001 fitness: 50.5000% 0.21040500 'NGVGIOJV IT JS MGLD CQBJQGDQUELSIJULMHYOGD VEAWCIMPYMUP'
#02000002 fitness: 22 0.3100% 0.17650500 'MGTGIOJS IU JS MGKDQBJQGDQUELSIJP CMHYOGD VEARELMPYMUQ'
#03000003 fitness: 60 0.6500% 0.09370500 'METHIOKS IU ISQBJQGFQUELSIJP LIKEMHYO BD VFASELMPYMUQ'
#03540004 fitness: 100 0.00% 0.02350500 'METHINKS ITQBJQGFQU ISLSIJP LIKEMHOO AD WEASELMPYMUQ'
#0005 fitness: 0.00% 0.0500 'QBJQGSQU LSIJP MHOO D MPYMFN'
#0006 fitness: 0.00% 0.0500 'QBJQGSQU LSIJP MHOO D MPCMFN'
#0007 fitness: 0.00% 0.0500 'QBRQGSQU LSIJP MHOO D MPCMFN'
#0008 fitness: 0.00% 0.0500 'QBRQGLQU LSIJP MHOE D MPCMFN'
...
#0097 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0098 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0099 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0100 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0101 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0102 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0103 fitness: 90.48% 0.0500 'METHIOKS IT IS LIKE A WEASEL'
#0104 fitness: 100.00% 0.0500 'METHINKS IT IS LIKE A WEASEL'
</pre>
 
=={{header|Amstrad CPC Locomotive BASIC}}==
Finding the target string on an Amstrad CPC takes a bit less than 45 minutes.
 
<syntaxhighlight lang="locobasic">10 s$="METHINKS IT IS LIKE A WEASEL"
20 cc=100
30 prop=0.05
40 sl=len(s$)
50 dim c(cc,sl)
60 dim o(sl)
70 dim v(cc)
80 cp = 1
90 start=time
100 for i=1 to sl
110 o(i)=asc(mid$(s$,i,1))
120 if o(i)=32 then o(i)=64
130 next
140 for j=1 to sl:c(1,j)=int(64+27*rnd(1)):next
150 for i=2 to cc
160 for j=1 to sl:c(i,j)=c(cp,j):next
170 next
180 for i=1 to cc
190 for j=1 to sl
200 if rnd(1)>prop then goto 220
210 c(i,j)=int(64+27*rnd(1))
220 next j: next i
230 sc=0:bsi=1
240 for i=1 to cc
250 v(i)=0
260 for j=1 to sl
270 if c(i,j)=o(j) then v(i)=v(i)+1
280 next j
290 if v(i)>sc then sc=v(i):bsi=i
300 next i
310 print sc"@"bsi;:if bsi<10 then print " ";
320 for i=1 to sl:?chr$(c(bsi, i)+(c(bsi, i)=64)*32);:next:?
330 if sc=sl then print "We have a weasel!":? "Time: "(time-start)/300:end
340 cp=bsi
350 goto 150</syntaxhighlight>
 
Output during calculation (excerpt):
<pre> 27 @ 10 METHINKGS IT IS LQKE A WEASEL
27 @ 9 METHINKGS IT IS LYKE A WEASEL
27 @ 2 METHINKGS IT IS LYKE A WEASEL
27 @ 2 METHINKGS IT IS LYKE A WEASEL
27 @ 7 METHINKGS IT IS LYKE A WEASEL
27 @ 2 METHINKGS IT IS LYKE A WEASEL
28 @ 93 METHINKGS IT IS LIKE A WEASEL
We have a weasel!
Time: 2572.87</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl"> evolve←{
⍺←0.1
target←'METHINKS IT IS LIKE A WEASEL'
Line 850 ⟶ 1,015:
}charset[?(⍴target)/⍴charset]
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 877 ⟶ 1,042:
METHINKS IT IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">target: "METHINKS IT IS LIKE A WEASEL"
alphabet: [` `] ++ @`A`..`Z`
p: 0.05
c: 100
 
 
negFitness: function [trial][
result: 0
loop 0..dec size trial 'i ->
if target\[i] <> trial\[i] -> inc 'result
return result
]
 
mutate: function [parent][
result: ""
loop parent 'c ->
'result ++ (p > random 0.0 1.0)? -> sample alphabet -> c
return result
]
 
parent: ""
do.times: size target ->
'parent ++ sample alphabet
 
j: 0
 
copies: []
while [parent <> target][
'copies ++ map c 'i -> mutate parent
 
best: first copies
loop 1..dec size copies 'i [
if (negFitness copies\[i]) < negFitness best ->
best: copies\[i]
]
parent: best
 
print [pad to :string j 2 parent]
inc 'j
]</syntaxhighlight>
 
{{out}}
 
<pre> 0 JBTBAFNWA YYZTOUBPIUUSPTFKYK
1 JBTBAFNWA YYFTOUBPIUU PTFKYK
2 MBTBAFNWA YYFTOUBPDUU PTFKYK
3 MBTBCMNWA YYFTOUBPDUU PTFKEK
4 MBTBCMNWA YDFSOUBPDUU PTFKEK
...
27 METHINVSV TDIS LIKE A WZASEK
28 METHINVSV TDIS LIKE A WZASEL
29 METHINVSV TDIS LIKE A WZASEL
30 METHINVSV TDIS LIKE A WZASEL
31 METHINVSV TDIS LIKE A WZASEL
32 METHINVSV TDIS LIKE A WZASEL
33 METHINVSV TDIS LIKE A WZASEL
34 METHINVSV TDIS LIKE A WZASEL
35 METHINVS TMIS LIKE A WZASEL
...
57 METHINVS ITMIS LIKE A WEASEL
58 METHINVS IT IS LIKE A WEASEL
59 METHINVS IT IS LIKE A WEASEL
60 METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">output := ""
target := "METHINKS IT IS LIKE A WEASEL"
targetLen := StrLen(target)
Line 935 ⟶ 1,166:
totalFit++
Return totalFit
}</langsyntaxhighlight>
Output:
<pre>10: DETRNNKR IAQPFLNVKZ AMXEASEL, fitness: 14
Line 949 ⟶ 1,180:
=={{header|AWK}}==
I apply the rate to each character in each generated child. The number of generations required seems to be really sensitive to the rate. I used the default seeding in GNU awk to obtain the results below. I suspect the algorithm used to generate the pseudo-random numbers may also influence the rapidity of convergence but I haven't investigated that yet. The output shown was obtained using GNU Awk 3.1.5. BusyBox v1.20.0.git also works but using the same rate generates 88 generations before converging.
<langsyntaxhighlight lang="awk">
#!/bin/awk -f
function randchar(){
Line 1,013 ⟶ 1,244:
}
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,029 ⟶ 1,260:
#
</pre>
 
=={{header|BASIC}}==
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> target$ = "METHINKS IT IS LIKE A WEASEL"
parent$ = "IU RFSGJABGOLYWF XSMFXNIABKT"
mutation_rate = 0.5
children% = 10
DIM child$(children%)
REPEAT
bestfitness = 0
bestindex% = 0
FOR index% = 1 TO children%
child$(index%) = FNmutate(parent$, mutation_rate)
fitness = FNfitness(target$, child$(index%))
IF fitness > bestfitness THEN
bestfitness = fitness
bestindex% = index%
ENDIF
NEXT index%
parent$ = child$(bestindex%)
PRINT parent$
UNTIL parent$ = target$
END
DEF FNfitness(text$, ref$)
LOCAL I%, F%
FOR I% = 1 TO LEN(text$)
IF MID$(text$, I%, 1) = MID$(ref$, I%, 1) THEN F% += 1
NEXT
= F% / LEN(text$)
DEF FNmutate(text$, rate)
LOCAL C%
IF rate > RND(1) THEN
C% = 63+RND(27)
IF C% = 64 C% = 32
MID$(text$, RND(LEN(text$)), 1) = CHR$(C%)
ENDIF
= text$</syntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
setlocal enabledelayedexpansion
Line 1,120 ⟶ 1,393:
for /l %%i in (1,1,28) do set %returnarray%=!%returnarray%! !%returnarray%%%i!
exit /b
</syntaxhighlight>
</lang>
{{out}}
Sample Output:
Line 1,154 ⟶ 1,427:
Done.
</pre>
 
=={{header|BBC BASIC}}==
<lang bbcbasic> target$ = "METHINKS IT IS LIKE A WEASEL"
parent$ = "IU RFSGJABGOLYWF XSMFXNIABKT"
mutation_rate = 0.5
children% = 10
DIM child$(children%)
REPEAT
bestfitness = 0
bestindex% = 0
FOR index% = 1 TO children%
child$(index%) = FNmutate(parent$, mutation_rate)
fitness = FNfitness(target$, child$(index%))
IF fitness > bestfitness THEN
bestfitness = fitness
bestindex% = index%
ENDIF
NEXT index%
parent$ = child$(bestindex%)
PRINT parent$
UNTIL parent$ = target$
END
DEF FNfitness(text$, ref$)
LOCAL I%, F%
FOR I% = 1 TO LEN(text$)
IF MID$(text$, I%, 1) = MID$(ref$, I%, 1) THEN F% += 1
NEXT
= F% / LEN(text$)
DEF FNmutate(text$, rate)
LOCAL C%
IF rate > RND(1) THEN
C% = 63+RND(27)
IF C% = 64 C% = 32
MID$(text$, RND(LEN(text$)), 1) = CHR$(C%)
ENDIF
= text$</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,263 ⟶ 1,495:
 
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text">iter 0, score 26: WKVVYFJUHOMQJNZYRTEQAGDVXKYC
iter 1, score 25: WKVVTFJUHOMQJN YRTEQAGDVSKXC
iter 2, score 25: WKVVTFJUHOMQJN YRTEQAGDVSKXC
Line 1,270 ⟶ 1,502:
iter 221, score 1: METHINKSHIT IS LIKE A WEASEL
iter 222, score 1: METHINKSHIT IS LIKE A WEASEL
iter 223, score 0: METHINKS IT IS LIKE A WEASEL</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 1,276 ⟶ 1,508:
{{works with|C sharp|C#|3+}}
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,329 ⟶ 1,561:
Console.WriteLine("END: #{0,6} {1,20}", i, parent);
}
}</langsyntaxhighlight>
 
Example output:
Line 1,400 ⟶ 1,632:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <cstdlib>
#include <iostream>
Line 1,509 ⟶ 1,741:
}
std::cout << "final string: " << parent << "\n";
}</langsyntaxhighlight>
Example output:
<pre>
Line 1,560 ⟶ 1,792:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
Line 1,608 ⟶ 1,840:
print("mutated into target in ``generationCount`` generations!");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Define the evolution parameters (values here per Wikipedia article), with a couple of problem constants.
<langsyntaxhighlight lang="clojure">(def c 100) ;number of children in each generation
(def p 0.05) ;mutation probability
 
Line 1,618 ⟶ 1,850:
(def tsize (count target))
 
(def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ")</langsyntaxhighlight>
Now the major functions. ''fitness'' simply counts the number of characters matching the target.
<langsyntaxhighlight lang="clojure">(defn fitness [s] (count (filter true? (map = s target))))
(defn perfectly-fit? [s] (= (fitness s) tsize))
 
(defn randc [] (rand-nth alphabet))
(defn mutate [s] (map #(if (< (rand) p) (randc) %) s))</langsyntaxhighlight>
Finally evolve. At each generation, print the generation number, the parent, and the parent's fitness.
<langsyntaxhighlight lang="clojure">(loop [generation 1, parent (repeatedly tsize randc)]
(println generation, (apply str parent), (fitness parent))
(if-not (perfectly-fit? parent)
(let [children (repeatedly c #(mutate parent))
fittest (apply max-key fitness parent children)]
(recur (inc generation), fittest))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">fitness = proc (s, t: string) returns (int)
f: int := 0
for i: int in int$from_to(1,string$size(s)) do
if s[i] ~= t[i] then f := f-1 end
end
return(f)
end fitness
 
mutate = proc (mut: int, s: string) returns (string)
own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
out: array[char] := array[char]$predict(1,string$size(s))
for c: char in string$chars(s) do
if random$next(10000) < mut then
c := charset[1+random$next(string$size(charset))]
end
array[char]$addh(out,c)
end
return(string$ac2s(out))
end mutate
 
weasel = iter (mut, c: int, tgt: string) yields (string)
own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
start: array[char] := array[char]$[]
for i: int in int$from_to(1,string$size(tgt)) do
array[char]$addh(start,charset[1+random$next(string$size(charset))])
end
cur: string := string$ac2s(start)
while true do
yield(cur)
if cur = tgt then break end
best: string := cur
best_fitness: int := fitness(cur, tgt)
for i: int in int$from_to(2,c) do
next: string := mutate(mut, cur)
next_fitness: int := fitness(next, tgt)
if best_fitness <= next_fitness then
best, best_fitness := next, next_fitness
end
end
cur := best
end
end weasel
 
start_up = proc ()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
po: stream := stream$primary_output()
for m: string in weasel(100, 1000, "METHINKS IT IS LIKE A WEASEL") do
stream$putl(po, m)
end
end start_up</syntaxhighlight>
{{out}}
<pre>CQWBQKNNFKEOLFLXHGJYEWZYULBQ
MQWBQKNNFKEOLFLXHGJYEWZYULBQ
MQWBQKNNFKEOLFLXHGJYEWZEULBQ
MEWBQKNNFKEOLFLXHGJYEWZEULBQ
MEWBQKNNFKEOLFLXHKJYEWZEULBQ
MEWBQKNNFKEOLFLXHKJYEWZEULBL
MEWBQNNNFKEOLFLXHKJYEWZEULBL
METBQNNNFKEOLFLXHKJYEWZEULBL
METBQNNNFKEOLFLXHKJYE ZEULBL
METBQNNSFKEOLFLXHKJYE ZEULBL
METBQNNSFKEOLFLXHKEYE ZEULBL
METBQNNSFKEOLFLXHKEYE ZEULEL
METBQNNSFKEOLFLXIKEYE ZEULEL
METEQNNSFKEOLFLLIKEYE ZEULEL
METEQNNSFKEOLFLLIKE E ZEULEL
METEQNKSFKEOLFLLIKE E ZEULEL
METEQNKSFKEOLF LIKE E ZEULEL
METEQNKSFKEOLF LIKE E ZEALEL
METEQNKSFKEOIF LIKE E ZEALEL
METEQNKSFKEOIF LIKE E ZEASEL
METEQNKSFKTOIF LIKE E ZEASEL
METEQNKS KTOIF LIKE E ZEASEL
METEQNKS KTOIF LIKE E WEASEL
METHQNKS KTOIF LIKE E WEASEL
METHQNKS ITOIF LIKE E WEASEL
METHQNKS ITOIF LIKE E WEASEL
METHQNKS ITOIF LIKE A WEASEL
METHQNKS IT IF LIKE A WEASEL
METHQNKS IT IF LIKE A WEASEL
METHQNKS IT IS LIKE A WEASEL
METHQNKS IT IS LIKE A WEASEL
METHQNKS IT IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|COBOL}}==
For testing purposes, you can comment out the first two sentences in the <tt>CONTROL-PARAGRAPH</tt> and the program will then use the same sequence of pseudo-random numbers on each run.
<langsyntaxhighlight lang="cobol">identification division.
program-id. evolutionary-program.
data division.
Line 1,722 ⟶ 2,041:
fittest-paragraph.
move fitness to highest-fitness.
move child to fittest.</langsyntaxhighlight>
{{out}}
<div style="height:50ex;overflow:scroll">
Line 1,922 ⟶ 2,241:
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfset theString = 'METHINKS IT IS LIKE A WEASEL'>
<cfparam name="parent" default="">
Line 1,990 ⟶ 2,309:
 
</Cfloop>
</syntaxhighlight>
</lang>
<pre>
#1 7% fit: VOPJOBSYPTTUNYYSAFHTPJUIAIL
Line 2,013 ⟶ 2,332:
#349 96% fit: METHINKS IT IS LIKE A WEASOL
#360 100% fit: METHINKS IT IS LIKE A WEASEL
</pre>
 
=={{header|Commodore BASIC}}==
Finding the target string takes roughly two hours on a Commodore 64.
 
<syntaxhighlight lang="gwbasic">10 N=100:P=0.05:TI$="000000"
20 Z$="METHINKS IT IS LIKE A WEASEL"
30 L=LEN(Z$)
40 DIMX(N,L)
50 FORI=1TOL
60 IFMID$(Z$,I,1)=" "THENX(0,I)=0:GOTO80
70 X(0,I)=ASC(MID$(Z$,I))-64
80 NEXT
90 FORK=1TON:FORI=1TOL:X(K,I)=INT(RND(0)*27):NEXT:NEXT
100 S=-100:B=0
110 K=B:GOSUB300
120 FORK=1TON:IFK=BTHEN150
130 FORI=1TOL:IFRND(.)<PTHENX(K,I)=INT(RND(0)*27)
140 NEXT
150 NEXT
160 S=-100:B=0
170 FORK=1TON
180 F=0:FORI=1TOL:IFX(K,I)<>X(0,I)THENF=F-1:IFF<STHENI=L
190 NEXT:IFF>STHENS=F:B=K
200 NEXT
210 PRINT"BEST:"B;"SCORE:"S
220 IFS=0THEN270
230 FORK=1TON:IFK=BTHEN250
240 FORI=1TOL:X(K,I)=X(B,I):NEXT
250 NEXT
260 GOTO110
270 PRINT"WE HAVE A WEASEL!":K=B:GOSUB300
280 PRINT"TIME:"TI$:END
300 FORI=1TOL:IFX(K,I)THENPRINTCHR$(64+X(K,I));:GOTO320
310 PRINT" ";
320 NEXT:PRINT"<":RETURN</syntaxhighlight>
 
Output during calculation (excerpt):
<pre>
BEST: 23 SCORE:-21
PJKJELKRRIWZITLOCKXTNYLNASEY<
BEST: 3 SCORE:-20
PJKJENKRRIWZITLOCKXTNJLNASEY<
BEST: 14 SCORE:-19
PJKJENKSRIWZITLOCKXTNJLNASEY<
BEST: 79 SCORE:-18
PJKJENKSRIW ITLOCKXTNJLNASEY<
BEST: 50 SCORE:-17
PJKUENKSRIW ITLOCKXTN LNASEY<
BEST: 12 SCORE:-16
PJKUINKSRIW ITLOCKHTN LNASEY<
BEST: 8 SCORE:-15
PJKUINKSSIK ITLOCKHTA LNASEY<
BEST: 21 SCORE:-14
PJKHINKSSIK ITLOCKHTA LNASEY<
BEST: 30 SCORE:-13
PJTHINKSSIK ITTOCKHTA LOASEY<
BEST: 48 SCORE:-12
PJTHINKS IK ITTOCKHTA LOASEY<
BEST: 1 SCORE:-12
PJTHINKS IK ITTOCKHTA LOASEY<
BEST: 29 SCORE:-11
PJTHINKS IK IT OCKHTA LOASEY<
</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun fitness (string target)
"Closeness of string to target; lower number is better"
(loop for c1 across string
Line 2,054 ⟶ 2,436:
(n 0 (1+ n)))
((string= target parent) (format t "Generation ~A: ~S~%" n parent))
(format t "Generation ~A: ~S~%" n parent))))</langsyntaxhighlight>
Sample output:
<pre>CL-USER> (evolve-gens "METHINKS IT IS LIKE A WEASEL" 100 0.05)
Line 2,104 ⟶ 2,486:
 
Mutates one character at a time, with only on offspring each generation (which competes against the parent):
<langsyntaxhighlight lang="lisp">(defun unfit (s1 s2)
(loop for a across s1
for b across s2 count(char/= a b)))
Line 2,126 ⟶ 2,508:
(format t "~5d: ~a (~d)~%" gen str fit))))
 
(evolve 1 " ABCDEFGHIJKLMNOPQRSTUVWXYZ" "METHINKS IT IS LIKE A WEASEL")</langsyntaxhighlight>outupt<syntaxhighlight lang="text"> 44: DYZTOREXDML ZCEUCSHRVHBEPGJE (26)
57: DYZTOREXDIL ZCEUCSHRVHBEPGJE (25)
83: DYZTOREX IL ZCEUCSHRVHBEPGJE (24)
Line 2,152 ⟶ 2,534:
1220: METHINKS IT IS LIKE AHBEASEL (2)
1358: METHINKS IT IS LIKE AHWEASEL (1)
2610: METHINKS IT IS LIKE A WEASEL (0)</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.range, std.ascii;
 
enum target = "METHINKS IT IS LIKE A WEASEL"d;
Line 2,172 ⟶ 2,554:
writefln("Gen %2d, dist=%2d: %s", gen, parent.fitness, parent);
}
}</langsyntaxhighlight>
{{out}}
<pre>Generation 0, dist=25: PTJNKPFVJFTDRSDVNUB ESJGU MF
Line 2,199 ⟶ 2,581:
Generation 23, dist= 1: METHINKS IT IS LIKE A WEASEW
Generation 24, dist= 0: METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|Dart}}==
{{trans|Java}}
<syntaxhighlight lang="Dart">
import 'dart:math';
 
class EvoAlgo {
static final String target = "METHINKS IT IS LIKE A WEASEL";
static final List<String> possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split('');
static int c = 100; // Number of spawn per generation
static double minMutateRate = 0.09;
static int perfectFitness = target.length;
static String parent = '';
static Random rand = Random();
 
static int fitness(String trial) {
int retVal = 0;
for (int i = 0; i < trial.length; i++) {
if (trial[i] == target[i]) retVal++;
}
return retVal;
}
 
static double newMutateRate() {
return (((perfectFitness - fitness(parent)) / perfectFitness) * (1 - minMutateRate));
}
 
static String mutate(String parent, double rate) {
String retVal = '';
for (int i = 0; i < parent.length; i++) {
retVal += (rand.nextDouble() <= rate)
? possibilities[rand.nextInt(possibilities.length)]
: parent[i];
}
return retVal;
}
 
static void main() {
parent = mutate(target, 1);
int iter = 0;
while (parent != target) {
double rate = newMutateRate();
iter++;
if (iter % 100 == 0) {
print('$iter: $parent, fitness: ${fitness(parent)}, rate: $rate');
}
String bestSpawn;
int bestFit = 0;
for (int i = 0; i < c; i++) {
String spawn = mutate(parent, rate);
int fit = fitness(spawn);
if (fit > bestFit) {
bestSpawn = spawn;
bestFit = fit;
}
}
if (bestFit > fitness(parent)) {
parent = bestSpawn;
}
}
print('$parent, $iter');
}
}
 
void main() {
EvoAlgo.main();
}
</syntaxhighlight>
{{out}}
<pre>
100: MFTHINFU IR N WLEKWKA WQZKYM, fitness: 13, rate: 0.4875
200: MXTHINPJ HR NNTLEKF A WDZHEH, fitness: 14, rate: 0.455
300: YNTHINPJ IK IS LEKNNA ADZHEL, fitness: 16, rate: 0.39
400: XETHI PS IKXIS LBKNDA QEUSEL, fitness: 18, rate: 0.325
500: NETHINPS I IS IBKLNA WEASEL, fitness: 21, rate: 0.2275
METHINKS IT IS LIKE A WEASEL, 551
 
</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Evolutionary_algorithm#Pascal Pascal].
 
=={{header|E}}==
<langsyntaxhighlight lang="e">pragma.syntax("0.9")
pragma.enable("accumulator")
 
Line 2,246 ⟶ 2,707:
}
 
weasel()</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
target$ = "METHINKS IT IS LIKE A WEASEL"
abc$[] = strchars " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"
P = 0.05
C = 100
func fitness trial$ .
for i to len trial$
res += if substr trial$ i 1 <> substr target$ i 1
.
return res
.
func$ mutate parent$ .
for c$ in strchars parent$
if randomf < P
res$ &= abc$[randint len abc$[]]
else
res$ &= c$
.
.
return res$
.
for i to len target$
parent$ &= abc$[randint len abc$[]]
.
while fitness parent$ > 0
copies$[] = [ ]
for i to C
copies$[] &= mutate parent$
.
parent$ = copies$[1]
for s$ in copies$[]
if fitness s$ < fitness parent$
parent$ = s$
.
.
step += 1
print step & " " & parent$
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(require 'sequences)
(define ALPHABET (list->vector ["A" .. "Z"] ))
Line 2,288 ⟶ 2,790:
(set! parent (select parent target rate copies))
))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,324 ⟶ 2,826:
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'text;
Line 2,343 ⟶ 2,845:
{
randomString()
= 0.repeatTill(self).selectBy::(x => randomChar).summarize(new StringWriter());
fitnessOf(s)
Line 2,349 ⟶ 2,851:
mutate(p)
= self.selectBy::(ch => rnd.nextReal() <= p ? randomChar : ch).summarize(new StringWriter());
}
 
class EvoAlgorithm : Enumerator
{
object theTarget_target;
object theCurrent_current;
object theVariantCount_variantCount;
 
constructor new(s,count)
{
theTarget_target := s;
theVariantCount_variantCount := count.toInt();
}
 
get Value() = theCurrent_current;
 
bool next()
{
if (nil == theCurrent_current)
{ theCurrent_current := theTarget_target.Length.randomString(); ^ true };
if (theTarget_target == theCurrent_current)
{ ^ false };
auto variants := Array.allocate(theVariantCount_variantCount).populate::(x => theCurrent_current.mutate:(P) );
theCurrent_current := variants.sort::(a,b => a.fitnessOf:(Target) > b.fitnessOf:(Target) ).at:(0);
^ true
Line 2,383 ⟶ 2,885:
reset()
{
theCurrent_current := nil
}
enumerable() => theTarget_target;
}
 
Line 2,392 ⟶ 2,894:
{
var attempt := new Integer();
EvoAlgorithm.new(Target,C).forEach::(current)
{
console
Line 2,400 ⟶ 2,902:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,455 ⟶ 2,957:
Print current gen and most fit offspring if more fit than parent.<br>
Print the target and the total number of generations (iterations) it took to reach it.<br>
<langsyntaxhighlight Elixirlang="elixir">defmodule Log do
def show(offspring,i) do
IO.puts "Generation: #{i}, Offspring: #{offspring}"
Line 2,518 ⟶ 3,020:
end
 
Evolution.select("METHINKS IT IS LIKE A WEASEL")</langsyntaxhighlight>
 
{{out}}
Line 2,576 ⟶ 3,078:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(evolution).
-export([run/0]).
 
Line 2,637 ⟶ 3,139:
random_string(N-1,[random_character()|Acc]).
 
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant table = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
function random_generation(integer len)
sequence s
Line 2,690 ⟶ 3,192:
iter += 1
end while
printf(1,"Finally, \"%s\"\n",{parent})</langsyntaxhighlight>
 
Output:
Line 2,718 ⟶ 3,220:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//A functional implementation of Evolutionary algorithm
//Nigel Galloway February 7th., 2018
Line 2,729 ⟶ 3,231:
evolution n []
let n = evolution (Array.init 28 (fun _->alphabet.[G.Next()%27]))
</syntaxhighlight>
</lang>
Real: 00:00:00.021, CPU: 00:00:00.050, GC gen0: 1, gen1: 0
<br>
Line 2,775 ⟶ 3,277:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays formatting io kernel literals math prettyprint
random sequences strings ;
FROM: math.extras => ... ;
Line 2,811 ⟶ 3,313:
"Finished in %d generations." printf ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,826 ⟶ 3,328:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 2,883 ⟶ 3,385:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|4tH|3.60.0}}
<langsyntaxhighlight lang="forth">include lib/choose.4th
\ target string
s" METHINKS IT IS LIKE A WEASEL" sconstant target
Line 2,959 ⟶ 3,461:
;
 
weasel</langsyntaxhighlight>
Output:
<pre>
Line 2,980 ⟶ 3,482:
{{works with|Fortran|2003}}
 
<langsyntaxhighlight lang="fortran">
!***************************************************************************************************
module evolve_routines
Line 3,116 ⟶ 3,618:
end program evolve
!***************************************************************************************************
</syntaxhighlight>
</lang>
 
The output is:
 
<syntaxhighlight lang="text">
iter best fitness
0 PACQXJB CQPWEYKSVDCIOUPKUOJY 459
Line 3,138 ⟶ 3,640:
70 MESHINKS IT IS LIKE A WEASEL 1
75 METHINKS IT IS LIKE A WEASEL 0
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 01-07-2018
' compile with: fbc -s console
 
Line 3,224 ⟶ 3,726:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>iteration best fit Parent
Line 3,258 ⟶ 3,760:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Weasel_program}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Evolutionary algorithm 01.png]]
In '''[https://formulae.org/?example=Weasel_program this]''' page you can see the program(s) related to this task and their results.
 
'''Test case'''
 
[[File:Fōrmulæ - Evolutionary algorithm 02.png]]
 
[[File:Fōrmulæ - Evolutionary algorithm 03.png]]
 
'''A graph of the fitness function'''
 
[[File:Fōrmulæ - Evolutionary algorithm 04.png]]
 
[[File:Fōrmulæ - Evolutionary algorithm 05.png]]
 
=={{header|Go}}==
I took the liberty to use <code>[]byte</code> for the "strings" mentioned in the task description. Go has a native string type, but in this case it was both easier and more efficient to work with byte slices and just convert to string when there was something to print.
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,330 ⟶ 3,844:
}
}
}</langsyntaxhighlight>
{{out}}
<div style='height: 15em; overflow: scroll'><pre>
Line 3,362 ⟶ 3,876:
{{works with|GHC|7.6.3}}
 
<langsyntaxhighlight Haskelllang="haskell">import System.Random
import Control.Monad
import Data.List
Line 3,409 ⟶ 3,923:
genes <- replicateM r $ randomRIO (bounds charSet)
let parent = map (charSet!) genes
evolve parent 1 mutateRate</langsyntaxhighlight>
Example run in GHCi:
<pre>*Main> main
Line 3,421 ⟶ 3,935:
I find this easier to read.
 
<langsyntaxhighlight Haskelllang="haskell">import System.Random
import Data.List
import Data.Ord
Line 3,455 ⟶ 3,969:
where fmtd = parent ++ ": " ++ show (fitness parent) ++ " (" ++ show n ++ ")"
 
main = origin >>= converge 0</langsyntaxhighlight>
Example:
<pre>YUZVNNZ SXPSNGZFRHZKVDOEPIGS: 2 (0)
Line 3,470 ⟶ 3,984:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">global target, chars, parent, C, M, current_fitness
 
procedure fitness(s)
Line 3,521 ⟶ 4,035:
write("At generation " || gen || " we found a string with perfect fitness at " || current_fitness || " reading: " || parent)
end
</syntaxhighlight>
</lang>
 
=={{Header|Insitux}}==
 
{{Trans|Clojure}}
 
Define the evolution parameters (values here per Wikipedia article), with a couple of problem constants.
 
<syntaxhighlight lang="insitux">
(var c 100) ;number of children in each generation
(var p 0.05) ;mutation probability
 
(var target "METHINKS IT IS LIKE A WEASEL")
(var tsize (len target))
 
(var alphabet (to-vec " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"))
 
</syntaxhighlight>
 
Now the major functions. <code>fitness</code> simply counts the number of characters matching the target.
 
<syntaxhighlight lang="insitux">
(var fitness (comp @(map = target) (count val)))
(var perfect-fit? (comp fitness (= tsize)))
 
(var rand-char #(rand-pick alphabet))
(var mutate (map #(if (< (rand) p) (rand-char) %)))
</syntaxhighlight>
 
Finally evolve. At each generation, print the generation number, the parent, and the parent's fitness.
 
<syntaxhighlight lang="insitux">
(function evolve generation parent
 
(print (pad-left " " 3 generation) " " (... str parent) " " (fitness parent))
 
(return-when (perfect-fit? parent))
 
(let children (times c #(mutate parent))
fittest (max-by fitness (... vec parent children)))
 
(recur (inc generation) fittest))
 
(evolve 1 (times tsize rand-char))
</syntaxhighlight>
 
{{out}}
 
<pre>
1 LUUDSLXITIQ JREKRDIQFXBPJMBA 2
2 LUUDSLXITIQ LREKRDIQFXBPHMEA 3
...
10 LUFRSLKSTIQ CFHLIGANB WPHMEL 10
11 LUFRSLKSTIQ CF LIGANB WPHMEL 11
...
20 MUTRINKSAIT GF LITENB WPDSEL 18
21 METRINKSAIT NY LITENB WPDSEL 19
...
30 METWINKS IT N LITE B WEASEL 23
31 METWINKS IT N LITE B WEASEL 23
...
40 METHINKS IT IS LITE A WEASEL 27
41 METHINKS IT IS LITE A WEASEL 27
...
50 METHINKS IT IS LITE A WEASEL 27
51 METHINKS IT IS LIKE A WEASEL 28
</pre>
 
=={{header|J}}==
Line 3,527 ⟶ 4,107:
'''Solution:'''<br>
Using sum of differences from the target for fitness, i.e. <code>0</code> is optimal fitness.
<langsyntaxhighlight lang="j">CHARSET=: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
NPROG=: 100 NB. number of progeny (C)
MRATE=: 0.05 NB. mutation rate
Line 3,540 ⟶ 4,120:
while =: conjunction def '(] , (u {:))^:(v {:)^:_ ,:'
evolve=: nextgen while (0 < fitness) create</langsyntaxhighlight>
 
'''Example usage:'''<br>
Returns list of best solutions at each generation until converged.
<langsyntaxhighlight lang="j"> filter=: {: ,~ ({~ i.@>.&.(%&20)@#) NB. take every 20th and last item
filter evolve 'METHINKS IT IS LIKE A WEASEL'
XXURVQXKQXDLCGFVICCUA NUQPND
MEFHINVQQXT IW LIKEUA WEAPEL
METHINVS IT IW LIKEUA WEAPEL
METHINKS IT IS LIKE A WEASEL</langsyntaxhighlight>
 
'''Alternative solution:'''<br>
Using explicit versions of <code>mutate</code> and <code>evolve</code> above.
<langsyntaxhighlight lang="j">CHARSET=: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
NPROG=: 100 NB. "C" from specification
 
Line 3,579 ⟶ 4,159:
log iter;val;parent
parent
)</langsyntaxhighlight>
 
'''Example Usage:'''
<langsyntaxhighlight lang="j"> evolve 'METHINKS IT IS LIKE A WEASEL'
#0 fitness: 27 ; YGFDJFTBEDB FAIJJGMFKDPYELOA
#50 fitness: 2 ; MEVHINKS IT IS LIKE ADWEASEL
#76 fitness: 0 ; METHINKS IT IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL</langsyntaxhighlight>
 
=={{header|Java}}==
Line 3,592 ⟶ 4,172:
 
'''(Close)''' {{trans|Python}}
<langsyntaxhighlight lang="java5">
import java.util.Random;
 
Line 3,650 ⟶ 4,230:
}
 
}</langsyntaxhighlight>
Output:
<pre>100: MEVHIBXSCG TP QIK FZGJ SEL, fitness: 13, rate: 0.4875
Line 3,661 ⟶ 4,241:
Using cross-browser techniques to support Array.reduce and Array.map
 
<langsyntaxhighlight lang="javascript">// ------------------------------------- Cross-browser Compatibility -------------------------------------
 
/* Compatibility code to reduce an array
Line 3,890 ⟶ 4,470:
document.write("Generation: " + generation + ", Best: " + fittest.individual.join("") + ", fitness:" + fittest.score + "<br>");
}
result = evolver.run(showProgress);</langsyntaxhighlight>
Output:
<pre>
Line 3,900 ⟶ 4,480:
Generation: 50, Best: METHINKS IT IS LIKEZA WEASEL, fitness:1
Generation: 52, Best: METHINKS IT IS LIKE A WEASEL, fitness:0
</pre>
 
 
An attempt using ES6
by A.K.Bateman 2023
<syntaxhighlight lang="javascript">
"use strict"
const TARGET = "METHINKS IT IS LIKE A WEASEL";
const GENE_POOL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ';
const C = 100;
const MUTATION_RATE = 0.3;
 
function randomIdGenerator(length) {
return Math.floor(Math.random() * length);
}
function getGene() {
return GENE_POOL[randomIdGenerator(GENE_POOL.length)];
}
 
class Parent {
_arrayLength;
_genePool;
_geneGenerator;
 
constructor(arrayLength, genePool, geneGenerator) {
if (typeof arrayLength === 'number' && arrayLength > 0) {
this._arrayLength = arrayLength;
}
 
if (typeof genePool === 'string' && genePool.length > 0) {
this._genePool = [...genePool];
}
 
if (typeof geneGenerator === 'function') {
this._geneGenerator = geneGenerator;
}
}
generate() {
const letters = [];
 
while (letters.length < this._arrayLength) {
letters.push(this._geneGenerator());
}
 
return letters.join('');
}
}
 
function fitness(needle, target) {
if (needle.length !== target.length) return 0;
 
const needleArray = [...needle];
let count = 0;
 
[...target].forEach((item, index) => {
if (item === needleArray[index]) count++;
});
 
return count;
}
 
function mutate({ source, mutationRate }) {
if (typeof source !== 'string' || source.length === 0) return '';
const sourceLength = source.length;
const iterations = Math.floor(sourceLength * mutationRate);
const stringArray = [...source];
 
for(let i = 0; i < iterations; i++) {
const shouldReplace = Boolean(Math.floor(Math.random() * 2));
 
if(shouldReplace) {
const id = randomIdGenerator(sourceLength);
stringArray[id] = getGene();
}
}
 
return stringArray.join('');
}
 
function createMutants(parent, mutantNumber) {
const mutantArray = [];
 
for (let i = 0; i < mutantNumber; i++) {
const mutant = mutate({source: parent, mutationRate: MUTATION_RATE});
 
mutantArray.push(
{
mutant,
fitness: fitness(mutant, TARGET),
},
);
}
 
return mutantArray;
}
 
function helperInit(parentString, parentFitness) {
const mutant = createMutants(parentString, C)
.sort( (a,b) => a.fitness - b.fitness ).pop();
 
if (mutant.fitness >= parentFitness) {
return {
string: mutant.mutant,
fitness: mutant.fitness,
};
}
 
return {
string: parentString,
fitness: parentFitness,
};
}
 
function run() {
const parent = new Parent(TARGET.length, GENE_POOL, getGene);
let parentString = parent.generate();
let parentFitness = fitness(parentString, TARGET);
let genCount = 0;
 
while(parentString !== TARGET) {
const init = helperInit(parentString, parentFitness);
parentString = init.string;
parentFitness = init.fitness;
console.log(init.string);
genCount++;
}
 
console.log(`Ended in ${genCount} generations`);
}
 
run();
</syntaxhighlight>
example output:
<pre>
METHYNKS IT IS LIKE A WEASEL
METHYNKS IT IS LIKE A WEASEL
METHYNKS IT IS LIKE A WEASEL
METHYNKS IT IS LIKE A WEASEL
METHYNKS IT IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL
Ended in 240 generations
</pre>
 
=={{header|jq}}==
{{Works with|jq}}
 
'''Works with gojq, the Go implementation of jq(*)'''
 
'''Works with jaq, the Rust implementation of jq(*)'''
 
In this entry, the "fitness" score is based on codepoint differences;
this has the effect of preserving correctly located spaces.
Notice also how the algorithm quickly achieves an approximate
solution but takes a while to arrive at the destination.
 
Since jq currently does not have a PRNG, the following assumes the availability
of /dev/random as a source of entropy. The output shown below was generated by
invoking jq in the pipeline:
<pre>
< /dev/random tr -cd '0-9' | fold -w 3 | $JQ -cnr -f evolutionary-algorithm.jq
</pre>
 
(*) For gojq and jaq, leading 0s must be stripped from the input, e.g. by
`sed -e '/^0./s/0//' -e '/^0./s/0//'`.
 
<syntaxhighlight lang="jq">
# Assumption: input consists of random three-digit numbers i.e. 000 to 999
def rand: input;
 
def set: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
 
def abs:
if . < 0 then -. else . end;
 
def ichar:
if type == "number" then . else explode[0] end;
 
# Output: a pseudo-random character from set.
# $n should be a random number drawn from range(0; N) inclusive where N > set|length
# Input: an admissible character from `set` (ignored in this implementation)
def shift($n):
($n % (set|length)) as $i
| set[$i:$i+1];
 
# fitness: 0 indicates a perfect fit; greater numbers indicate worse fit.
def fitness($gold):
def diff($c; $d): ($c|ichar) - ($d|ichar) | abs;
. as $in
| reduce range(0;length) as $i (0; . + diff($in[$i:$i+1]; $gold[$i:$i+1]));
 
# Input: a string
# Output: a mutation of . such that each character is mutated with probability $r
def mutate($r):
# Output: a pseudo-random character from set
# $n should be a random number drawn from range(0; N) inclusive where N > set|length
def letter($n):
($n % (set|length)) as $i
| set[$i:$i+1];
 
. as $p
| reduce range(0;length) as $i ("";
rand as $rand
| if ($rand/1000) < $r then . + letter($rand)
else . + $p[$i:$i+1]
end );
 
# An array of $n children of the parent provided as input; $r is the mutation probability
def children($n; $r):
[range(0;$n) as $i | mutate($r)];
 
# Input: a "parent"
# Output: a single string
def next_generation($gold; $r):
([.] + children(100; $r))
| min_by( fitness($gold) );
 
# Evolve towards the target string provided as input, using $r as the mutation rate;
# `recurse` is used in order to show progress conveniently.
def evolve($r):
. as $gold
| (set|length) as $s
| (reduce range(0; $n) as $i (""; (rand % $s) as $j | . + set[$j:$j+1])) as $string
| {count: 0, $string }
| recurse (
if .string | fitness($gold) == 0 then empty
else .string |= next_generation($gold; $r)
| .count += 1
end);
 
"METHINKS IT IS LIKE A WEASEL" | evolve(0.05)
</syntaxhighlight>
{{output}}
<pre>
{"count":0,"string":"OIRSP AVNMTSSKOEIRBGDXZUBIQL"}
{"count":1,"string":"OIRSP AV MTSSKOEIRBGDXZUBIQL"}
{"count":2,"string":"OIRSP AV MTSAKOEIRBGD ZUBIQL"}
{"count":3,"string":"OIRSPCAV MTSAWOEIRBGD ZUBIQL"}
{"count":4,"string":"OIRJACAV MTEAWOEIRBGD ZUBIQL"}
{"count":5,"string":"OIRJACTV MTEAWOEIRBGD ZGBIQL"}
{"count":6,"string":"OIRJBCTV MTEAWAEIRBGD ZGBIJL"}
{"count":7,"string":"OIRJBCTV MTEAWAEIRBGD ZGBTJL"}
{"count":8,"string":"UIRJBCTV MT AWFEIRBGG ZGBTJL"}
{"count":9,"string":"UIRJBMTV MT AWFEIRBGG ZGBTJL"}
{"count":10,"string":"JIRJEMTV MT AWFEIKGGG ZGBTJL"}
{"count":11,"string":"JIRJEMKV MT AWFEIKGGG XGBTJL"}
{"count":12,"string":"JIRJEMKV MT AWFEIKGGG XGBTAL"}
{"count":13,"string":"JIRJEMKV MT KWFEIKGGG XGBTAL"}
{"count":14,"string":"JFRJEMKP MT KWFEIKGGG XGBTAL"}
{"count":15,"string":"JFRJEMKP MT KWFJIKGGG XGBTAL"}
{"count":16,"string":"JFRJEMKT MT KQFJIKGGG XGBTAL"}
{"count":17,"string":"JFRJEMKT MT HQFJIKGGG XGBTAL"}
{"count":18,"string":"JFRJEMKT MT HQFJIKGGC XGBTAL"}
{"count":19,"string":"LFRJEMKT MT HQFJIIGGC XGATFL"}
{"count":20,"string":"LFRJIMKT MT HQFJIIGGC XGATFL"}
...
{"count":61,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":62,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":63,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":64,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":65,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":66,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":67,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":68,"string":"MFTHINKS JT IR LIKE A WEAREL"}
{"count":69,"string":"MFTHINKS IT IR LIKE A WEAREL"}
{"count":70,"string":"MFTHINKS IT IR LIKE A WEAREL"}
{"count":71,"string":"MFTHINKS IT IS LIKE A WEAREL"}
{"count":72,"string":"MFTHINKS IT IS LIKE A WEAREL"}
{"count":73,"string":"MFTHINKS IT IS LIKE A WEAREL"}
{"count":74,"string":"MFTHINKS IT IS LIKE A WEAREL"}
{"count":75,"string":"MFTHINKS IT IS LIKE A WEAREL"}
{"count":76,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":77,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":78,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":79,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":80,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":81,"string":"METHINKS IT IS LIKE A WEAREL"}
{"count":82,"string":"METHINKS IT IS LIKE A WEASEL"}
</pre>
 
Line 3,905 ⟶ 4,762:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">fitness(a::AbstractString, b::AbstractString) = count(l == t for (l, t) in zip(a, b))
function mutate(str::AbstractString, rate::Float64)
L = collect(Char, " ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Line 3,928 ⟶ 4,785:
end
 
evolve("IU RFSGJABGOLYWF XSMFXNIABKT", "METHINKS IT IS LIKE A WEASEL", 0.08998, 100)</langsyntaxhighlight>
 
{{out}}
Line 3,943 ⟶ 4,800:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.util.*
 
val target = "METHINKS IT IS LIKE A WEASEL"
Line 3,976 ⟶ 4,833:
}
println("Evolution found target after $i generations")
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">C = 10
'mutaterate has to be greater than 1 or it will not mutate
mutaterate = 2
Line 4,047 ⟶ 4,904:
End If
Next i
End Function</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "target "|METHINKS IT IS LIKE A WEASEL|
 
to distance :w
Line 4,093 ⟶ 4,950:
make "trials :trials + 1
]
end</langsyntaxhighlight>
 
=={{header|Lua}}==
{{works with|Lua|5.1+}}
 
<langsyntaxhighlight lang="lua">local target = "METHINKS IT IS LIKE A WEASEL"
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
local c, p = 100, 0.06
Line 4,149 ⟶ 5,006:
parent, step = bestChild, step + 1
printStep(step, parent, bestFitness)
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Version 1===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module WeaselAlgorithm {
Print "Evolutionary Algorithm"
Line 4,212 ⟶ 5,069:
WeaselAlgorithm
 
</syntaxhighlight>
</lang>
{{out}}
 
Line 4,254 ⟶ 5,111:
Also here we have one Mutate function which change letters using 5% probability for each place in the parent string.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module WeaselAlgorithm2 {
Print "Evolutionary Algorithm"
Line 4,308 ⟶ 5,165:
}
WeaselAlgorithm2
</syntaxhighlight>
</lang>
 
=={{header|m4}}==
 
This is written in POSIX m4, but seems to run least annoyingly in GNU m4. (For instance, OpenBSD m4 may resist attempts to use the interrupt key.)
 
You may lose patience with it, but it is written in m4, not optimized Fortran. I have run it successfully to completion.
 
Note that it writes to a file called ‘__random_number__’. The random number generator here is the best I have come up with that works in all the m4 implementations I have installed. (Something using sysval did not work in OpenBSD m4.)
 
This is not the best use of m4, and I am far from an m4 guru, but it seemed unlikely anyone else was going to write an m4 example for this task. The better my m4 skills, the better I am going to be at ''everything'' that can be preprocessed, and at GNU Autotools (which, unlike many, I like a lot). So I wrote this.
 
<syntaxhighlight lang="m4">divert(-1)
 
# Get a random number from 0 to one less than $1.
# (Note that this is not a very good RNG. Also it writes a file.)
#
# Usage: randnum(N) (Produces a random integer in 0..N-1)
#
define(`randnum',
`syscmd(`echo $RANDOM > __random_number__')eval(include(__random_number__) % ( $1 ))')
 
# The *target* specified in the Rosetta Code task.
define(`target',`METHINKS IT IS LIKE A WEASEL')
 
define(`alphabet',`ABCDEFGHIJKLMNOPQRSTUVWXYZ ')
define(`random_letter',`substr(alphabet,randnum(len(alphabet)),1)')
 
define(`create_primogenitor',`_$0(`')')
define(`_create_primogenitor',`ifelse(len(`$1'),len(target),`$1',
`$0(`$1'random_letter)')')
 
# The *parent* specified in the Rosetta Code task.
define(`parent',`'create_primogenitor)
 
#
# Usage: mutate_letter(STRING,INDEX)
#
define(`mutate_letter',
`substr(`$1',0,`$2')`'random_letter`'substr(`$1',incr(`$2'))')
 
#
# Usage: mutate_letter_at_rate(STRING,INDEX,MUTATION_RATE)
#
define(`mutate_letter_at_rate',
`ifelse(eval(randnum(100) < ($3)),1,`mutate_letter(`$1',`$2')',`$1')')
 
# The *mutate* procedure specified in the Rosetta Code task. The
# mutation rate is given in percents.
#
# Usage: mutate(STRING,MUTATION_RATE)
#
define(`mutate',`_$0(`$1',`$2',len(`$1'))')
define(`_mutate',
`ifelse($3,0,`$1',
`$0(mutate_letter_at_rate(`$1',decr($3),`$2'),`$2',decr($3))')')
 
# The *fitness* procedure specified in the Rosetta Code
# task. "Fitness" here is simply how many letters match.
#
# Usage: fitness(STRING)
#
define(`fitness',`_$0(`$1',target,0)')
define(`_fitness',
`ifelse(`$1',`',$3,
`ifelse(`'substr(`$1',0,1),`'substr(`$2',0,1),
`$0(`'substr(`$1',1),`'substr(`$2',1),incr($3))',
`$0(`'substr(`$1',1),`'substr(`$2',1),$3)')')')
 
#
# Usage: have_child(PARENT,MUTATION_RATE)
#
# The result is either the parent or the child: whichever has the
# greater fitness. If they are equally fit, one is chosen arbitrarily.
# (Note that, in the current implementation, fitnesses are not
# memoized.)
#
define(`have_child',
`pushdef(`_child_',mutate(`$1',`$2'))`'dnl
ifelse(eval(fitness(`'_child_) < fitness(`$1')),1,`$1',`_child_')`'dnl
popdef(`_child_')')
 
#
# Usage: next_parent(PARENT,NUM_CHILDREN,MUTATION_RATE)
#
# Note that a string is discarded as soon as it is known it will not
# be in the next generation. If some strings have the same highest
# fitness, one of them is chosen arbitrarily.
#
define(`next_parent',`_$0(`$1',`$2',`$3',`$1')')
define(`_next_parent',
`ifelse(`$2',0,`$1',
`$0(`'have_child(`$4',`$3'),decr(`$2'),`$3',`$4')')')
 
define(`repeat_until_equal',
`ifelse(`$1',`'target,`[$1]',
`pushdef(`_the_horta_',`'next_parent(`$1',`$2',`$3'))`'dnl
[_the_horta_]
$0(`'_the_horta_,`$2',`$3')`'dnl
popdef(`_the_horta_')')')
 
divert`'dnl
[parent]
repeat_until_equal(parent,10,10)</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">target = "METHINKS IT IS LIKE A WEASEL";
alphabet = Append[CharacterRange["A", "Z"], " "];
fitness = HammingDistance[target, #] &;
Line 4,327 ⟶ 5,287:
mutate[target, 1],
fitness@# > 0 &
] // ListAnimate</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 4,334 ⟶ 5,294:
To use this code, create a folder in your MATLAB directory titled "@EvolutionaryAlgorithm". Within that folder save this code in a file named "EvolutionaryAlgorithm.m".
 
<langsyntaxhighlight MATLABlang="matlab">%This class impliments a string that mutates to a target
classdef EvolutionaryAlgorithm
Line 4,553 ⟶ 5,513:
end %methods
end %classdef</langsyntaxhighlight>
Sample Output: (Some evolutionary cycles omitted for brevity)
<langsyntaxhighlight MATLABlang="matlab">>> instance = EvolutionaryAlgorithm('METHINKS IT IS LIKE A WEASEL',.08,50,1000)
Target: METHINKS IT IS LIKE A WEASEL
Parent: UVEOCXXFBGDCSFNMJQNWTPJ PCVA
Line 4,581 ⟶ 5,541:
100: METHIXKS YT IS LIKE A WEASEL - Fitness: 26
150: METHINKS YT IS LIKE A WEASEL - Fitness: 27
195: METHINKS IT IS LIKE A WEASEL - Fitness: 28</langsyntaxhighlight>
 
 
Line 4,588 ⟶ 5,548:
 
Presented is very efficient and vectorized version of the genetic algorithm. To run the algorithm simply copy and paste the code into a script and hit run. You can adjust the style of selection and crossover used to learn more about how they effect solutions. The algorithm can also handle any target string that uses ASCII characters and will allow for any phrase to be used regardless of length.
<syntaxhighlight lang="matlab">
<lang MATLAB>
%% Genetic Algorithm -- Solves For A User Input String
 
Line 4,699 ⟶ 5,659:
 
toc % Ends timer and prints elapsed time
</syntaxhighlight>
</lang>
 
Sample Output: (The Algorithm was run with 1000 population members, Tournament Selection (with tournament size of 4), 1-Point Crossover, and a mutation rate of 10%).
<syntaxhighlight lang="matlab">
<lang MATLAB>
Gen: 1 | Fitness: 465 | C�I1%G+<%?R�8>9�JU#(E�UO�PHI
Gen: 2 | Fitness: 429 | W=P6>D�I)VU6$T 99,� B�BMP0JH
Line 4,745 ⟶ 5,705:
Gen: 46 | Fitness: 0 | METHINKS IT IS LIKE A WEASEL
Elapsed time is 0.099618 seconds.
</syntaxhighlight>
</lang>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.Util
 
target = "METHINKS IT IS LIKE A WEASEL"
Line 4,831 ⟶ 5,791:
 
iter += 1
end</langsyntaxhighlight>
 
{{out}}
Line 4,854 ⟶ 5,814:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import random
 
const
Line 4,890 ⟶ 5,850:
 
echo i, " ", parent
inc i</langsyntaxhighlight>
 
{{out}}
Line 4,905 ⟶ 5,865:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">bundle Default {
class Evolutionary {
target : static : String;
Line 4,995 ⟶ 5,955:
}
}
}</langsyntaxhighlight>
 
Output:
Line 5,018 ⟶ 5,978:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let target = "METHINKS IT IS LIKE A WEASEL"
let charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
let tlen = String.length target
Line 5,058 ⟶ 6,018:
incr i
done;
Printf.printf "%5d - '%s'\n" !i parent</langsyntaxhighlight>
 
=={{header|Octave}}==
{{trans|R}}
 
<langsyntaxhighlight lang="octave">global target;
target = split("METHINKS IT IS LIKE A WEASEL", "");
charset = ["A":"Z", " "];
Line 5,115 ⟶ 6,075:
endwhile
disp(parent');
</syntaxhighlight>
</lang>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">200 Constant new: C
5 Constant new: RATE
Line 5,138 ⟶ 6,098:
ListBuffer init(C, #[ parent mutate ]) dup add(parent)
maxFor(#[ target fitness ]) dup ->parent . dup println 1+
] drop ;</langsyntaxhighlight>
 
{{out}}
Line 5,184 ⟶ 6,144:
=={{header|OoRexx}}==
Run with Open Object Rexx 4.1.0 by IBM Corporation 1995,2004 Rexx LA 2005-2010. Host OS: Microsoft Windows 7.
<langsyntaxhighlight lang="oorexx">
/* Weasel.rex - Me thinks thou art a weasel. - G,M.D. - 2/25/2011 */
arg C M
Line 5,239 ⟶ 6,199:
end
return result
</syntaxhighlight>
</lang>
Output:
<div style='height: 15em; overflow: scroll'><pre>
Line 5,277 ⟶ 6,237:
=={{header|OxygenBasic}}==
The algorithm pared down to the essentials. It takes around 1200 to 6000 mutations to attain the target. Fitness is measured by the number of beneficial mutations. The cycle ends when this is equal to the string length.
<langsyntaxhighlight lang="oxygenbasic">
 
'EVOLUTION
Line 5,318 ⟶ 6,278:
end do
print progeny " " gens 'RESULT (range 1200-6000 generations)
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
Target = "METHINKS IT IS LIKE A WEASEL"
C = 100
Line 5,380 ⟶ 6,340:
end
in
{Main}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 5,386 ⟶ 6,346:
 
This code is inefficient (tens of milliseconds) since it converts back and forth between string and vector format. A more efficient version would keep the information in a Vecsmall instead.
<langsyntaxhighlight lang="parigp">target="METHINKS IT IS LIKE A WEASEL";
fitness(s)=-dist(Vec(s),Vec(target));
dist(u,v)=sum(i=1,min(#u,#v),u[i]!=v[i])+abs(#u-#v);
Line 5,431 ⟶ 6,391:
ct;
}
evolve(35,.05)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 5,437 ⟶ 6,397:
This Pascal version of the program displays the initial random string and every hundredth generation after that. It also displays the final generation count. Mutation happens relatively slowly, about once in every 1000 characters, but this can be changed by altering the RATE constant. Lower values for RATE actually speed up the mutations.
 
<langsyntaxhighlight lang="pascal">PROGRAM EVOLUTION (OUTPUT);
 
CONST
Line 5,544 ⟶ 6,504:
WRITE('The string was matched in ');
WRITELN(GENERATIONS, ' generations.')
END.</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 5,550 ⟶ 6,510:
This implementation usually converges in less than 70 iterations.
 
<langsyntaxhighlight lang="perl">use List::Util 'reduce';
use List::MoreUtils 'false';
 
Line 5,594 ⟶ 6,554:
map {mutate $mutation_rate, $parent}
1 .. $C;
print @$parent, "\n";}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant target = "METHINKS IT IS LIKE A WEASEL",
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
AZS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
<span style="color: #008080;">constant</span> <span style="color: #000000;">target</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"METHINKS IT IS LIKE A WEASEL"</span><span style="color: #0000FF;">,</span>
C = 5000, -- children in each generation
<span style="color: #000000;">AZS</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ABCDEFGHIJKLMNOPQRSTUVWXYZ "</span><span style="color: #0000FF;">,</span>
P = 15 -- probability of mutation (1 in 15)
<span style="color: #000000;">C</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5000</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- children in each generation</span>
<span style="color: #000000;">P</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">15</span> <span style="color: #000080;font-style:italic;">-- probability of mutation (1 in 15)</span>
function fitness(string sample, string target)
return sum(sq_eq(sample,target))
<span style="color: #008080;">function</span> <span style="color: #000000;">fitness</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">sample</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">target</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sample</span><span style="color: #0000FF;">,</span><span style="color: #000000;">target</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function mutate(string s, integer n)
for i=1 to length(s) do
<span style="color: #008080;">function</span> <span style="color: #000000;">mutate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if rand(n)=1 then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
s[i] = AZS[rand(length(AZS))]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">AZS</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">AZS</span><span style="color: #0000FF;">))]</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
string parent = mutate(target,1) -- (mutate with 100% probability)
sequence samples = repeat(0,C)
<span style="color: #004080;">string</span> <span style="color: #000000;">parent</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mutate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">target</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mutate with 100% probability)</span>
integer gen = 0, best, fit, best_fit = fitness(parent,target)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">samples</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">C</span><span style="color: #0000FF;">)</span>
while parent!=target do
<span style="color: #004080;">integer</span> <span style="color: #000000;">gen</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">best</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">best_fit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fitness</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">target</span><span style="color: #0000FF;">)</span>
printf(1,"Generation%3d: %s, fitness %3.2f%%\n", {gen, parent, (best_fit/length(target))*100})
<span style="color: #008080;">while</span> <span style="color: #000000;">parent</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">target</span> <span style="color: #008080;">do</span>
best_fit = -1
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Generation%3d: %s, fitness %3.2f%%\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">gen</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">parent</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">best_fit</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">target</span><span style="color: #0000FF;">))*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span>
for i=1 to C do
<span style="color: #000000;">best_fit</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
samples[i] = mutate(parent, P)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">C</span> <span style="color: #008080;">do</span>
fit = fitness(samples[i], target)
<span style="color: #000000;">samples</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mutate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">P</span><span style="color: #0000FF;">)</span>
if fit > best_fit then
<span style="color: #000000;">fit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fitness</span><span style="color: #0000FF;">(</span><span style="color: #000000;">samples</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">target</span><span style="color: #0000FF;">)</span>
best_fit = fit
<span style="color: #008080;">if</span> <span style="color: #000000;">fit</span> <span style="color: #0000FF;">></span> <span style="color: #000000;">best_fit</span> <span style="color: #008080;">then</span>
best = i
<span style="color: #000000;">best_fit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fit</span>
end if
<span style="color: #000000;">best</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
parent = samples[best]
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
gen += 1
<span style="color: #000000;">parent</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">samples</span><span style="color: #0000FF;">[</span><span style="color: #000000;">best</span><span style="color: #0000FF;">]</span>
end while
<span style="color: #000000;">gen</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
printf(1,"Finally, \"%s\"\n",{parent})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Finally, \"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">parent</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 5,655 ⟶ 6,618:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');
Line 5,702 ⟶ 6,665:
} while($best);
 
</syntaxhighlight>
</lang>
Sample Output:
<pre>
Line 5,712 ⟶ 6,675:
Generation 178, score 0: METHINKS IT IS LIKE A WEASEL
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
_ = random2(),
Target = "METHINKS IT IS LIKE A WEASEL",
Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
C = 50, % Population size in each generation
M = 80, % Mutation rate per individual in a generation (0.8)
 
evo(Target,Chars,C,M),
 
nl.
 
 
evo(Target,Chars,C,M) =>
if member(T,Target), not member(T, Chars) then
printf("The character %w is not in the character set: %w\n", T, Chars);
halt
end,
 
% first random string
TargetLen = Target.length,
Parent = random_chars(Chars,TargetLen),
%
% Until current fitness reaches a score of perfect match
% with the target string keep generating new populations
%
CurrentFitness = 0,
Gen = 1,
while (CurrentFitness < TargetLen)
println([gen=Gen, currentFitness=CurrentFitness, parent=Parent]),
Gen := Gen + 1,
[Parent2,CurrentFitness2] = generation(C,Chars,Target,M,Parent),
CurrentFitness := CurrentFitness2,
Parent := Parent2
end,
 
println([gen=Gen, currentFitness=CurrentFitness, parent=Parent]),
printf("\nFound a perfect fitness (%d) at generation %d\n", CurrentFitness, Gen),
nl.
 
%
% Generate a random string
%
random_chars(Chars, N) = [Chars[my_rand(Len)] : _ in 1..N] =>
Len = Chars.length.
 
%
% Increment the fitness for every position in the string
% S that matches the target
%
fitness(S,Target) = sum([1: I in 1..Target.length, S[I] == Target[I]]).
 
 
%
% If a random number between 1 and 100 is inside the
% bounds of mutation randomly alter a character in the string
%
mutate(S,M,Chars) = S2 =>
S2 = copy_term(S),
if my_rand(100) <= M then
S2[my_rand(S.length)] := Chars[my_rand(Chars.length)]
end.
 
% Get a random value between 1 and N
my_rand(N) = 1+(random() mod N).
 
%
% Create the next population of parent
%
generation(C,Chars,Target,M,Parent) = [NextParent,NextFitness] =>
% generate a random population
Population = [mutate(Parent,M,Chars) : _ in 1..C],
 
% Find the member of the population with highest fitness,
NextParent = Parent,
NextFitness = fitness(Parent,Target),
foreach(X in Population)
XF = fitness(X,Target),
if XF > NextFitness then
NextParent := X,
NextFitness := XF
end
end.</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
This example uses 'gen', the genetic function in "lib/simul.l"
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(setq *Target (chop "METHINKS IT IS LIKE A WEASEL"))
Line 5,751 ⟶ 6,801:
C ) ) # return the current char
A ) )
fitness ) # Selection function</langsyntaxhighlight>
Output:
<pre>RQ ASLWWWI ANSHPNABBAJ ZLTKX
Line 5,766 ⟶ 6,816:
the rate is fixed at 2 as that is the lowest most successful rate still in the spirit of the original proposal (where mutation allows a previously successful change to be undone). if the rate is 1 than every successful character change can not change again (because it would not cause an improvement and thus be rejected.)
 
<langsyntaxhighlight Pikelang="pike">string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
 
string mutate(string data, int rate)
Line 5,809 ⟶ 6,859:
}
}
}</langsyntaxhighlight>
 
Output:
Line 5,844 ⟶ 6,894:
=={{header|Pony}}==
{{trans|Java}}
<langsyntaxhighlight Ponylang="pony">use "random"
 
actor Main
Line 5,916 ⟶ 6,966:
end
end
consume ret_val</langsyntaxhighlight>
Output:
<pre>100: UMMMDNKR IEIIB IIKZ A THAHEL, fitness: 14, rate: 0.455
Line 5,927 ⟶ 6,977:
'''Alternative solution:'''<br>
Using a more OO approach that leverages classes for encapsulation.
<langsyntaxhighlight Ponylang="pony">use "random"
use "collections"
 
Line 6,041 ⟶ 7,091:
until best.string == desired.string end
 
env.out.print(best.string + ", " + iterations.string())</langsyntaxhighlight>
 
Output:
Line 6,052 ⟶ 7,102:
=={{header|Prolog}}==
{{works with|SWI Prolog|6.2.6 by Jan Wielemaker, University of Amsterdam}}
<langsyntaxhighlight Prologlang="prolog">target("METHINKS IT IS LIKE A WEASEL").
 
rndAlpha(64, 32). % Generate a single random character
Line 6,083 ⟶ 7,133:
weasel :- % Chance->probability for a mutation, T=Target, Start=initial text
target(T), length(T, Len), rndTxt(Len, Start), Chance is 1 - (1/(Len+1)),
!, weasel(0, Chance, T, Start).</langsyntaxhighlight>
Output:
<pre> time(weasel).
Line 6,104 ⟶ 7,154:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Define population = 100, mutationRate = 6
Define.s target$ = "METHINKS IT IS LIKE A WEASEL"
Define.s charSet$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
Line 6,174 ⟶ 7,224:
Wend
 
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</langsyntaxhighlight>
 
=={{header|Python}}==
Using lists instead of strings for easier manipulation, and a mutation rate that gives more mutations the further the parent is away from the target.
<langsyntaxhighlight lang="python">from string import letters
from random import choice, random
Line 6,224 ⟶ 7,274:
parent2 = max(copies[center:], key=fitness)
parent = max(mate(parent1, parent2), key=fitness)
que()</langsyntaxhighlight>
 
Sample output
Line 6,234 ⟶ 7,284:
 
A simpler Python version that converges in less steps:
<langsyntaxhighlight lang="python">from random import choice, random
 
target = list("METHINKS IT IS LIKE A WEASEL")
Line 6,254 ⟶ 7,304:
parent = min(copies, key=neg_fitness)
print "%3d" % i, "".join(parent)
i += 1</langsyntaxhighlight>
 
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">set.seed(1234, kind="Mersenne-Twister")
 
## Easier if the string is a character vector
Line 6,309 ⟶ 7,359:
}
}
.printGen(parent, target, i)</langsyntaxhighlight>
 
output:
Line 6,325 ⟶ 7,375:
Very close to former solution, but a bit easier.
 
<langsyntaxhighlight Rlang="r"># Setup
set.seed(42)
target= unlist(strsplit("METHINKS IT IS LIKE A WEASEL", ""))
Line 6,358 ⟶ 7,408:
parent= evolve(parent)
cat(paste0(parent, collapse=""), "\n")
}</langsyntaxhighlight>
 
 
Line 6,370 ⟶ 7,420:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 6,408 ⟶ 7,458:
(printf "~s Total strings: ~s\n" C (for/sum ([n ns]) (* n 50))))
(for ([C (in-range 10 501 10)]) (try-run C 0.001))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|20152022-1107-1109}}
<syntaxhighlight lang="raku" perl6line>constant target = "METHINKS IT IS LIKE A WEASEL";
constant mutate_chance = .08;
constant @alphabet = flat 'A'..'Z',' ';
constant C = 10010;
 
sub mutate(Str $string, Real $mutate-chance where 0 ≤ * < 1) {
sub mutate { [~] (rand < mutate_chance ?? @alphabet.pick !! $_ for $^string.comb) }
$string.subst: /<?{ rand < $mutate-chance }> . /, @alphabet.pick, :global
sub fitness { [+] $^string.comb Zeq target.comb }
}
sub fitness(Str $string) { [+] $string.comb Zeq target.comb }
 
printf "\r%6d: '%s'", $++, $_ for
loop (
my $parent = @alphabet.roll(target.chars).join;,
{ max :by(&fitness), mutate($parent_, .001) xx C } ne... target;
print "\n";
$parent = max :by(&fitness), mutate($parent) xx C
</syntaxhighlight>
) { printf "%6d: '%s'\n", $++, $parent }</lang>
 
=={{header|Red}}==
 
<syntaxhighlight lang="red">Red[]
 
; allowed characters
alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
; target string
target: "METHINKS IT IS LIKE A WEASEL"
; parameter controlling the number of children
C: 10
; parameter controlling the evolution rate
RATE: 0.05
 
; compute closeness of 'string' to 'target'
fitness: function [string] [
sum: 0
 
repeat i length? string [
if not-equal? pick string i pick target i [
sum: sum + 1
]
]
 
sum
]
 
; return copy of 'string' with mutations, frequency based on given 'rate'
mutate: function [string rate] [
result: copy string
 
repeat i length? result [
if rate > random 1.0 [
poke result i random/only alphabet
]
]
 
result
]
 
; create initial random parent
parent: ""
repeat i length? target [
append parent random/only alphabet
]
 
; main loop, displaying progress
while [not-equal? parent target] [
print parent
children: copy []
 
repeat i C [
append children mutate parent RATE
]
sort/compare children function [a b] [lesser? fitness a fitness b]
 
parent: pick children 1
]
print parent
</syntaxhighlight>
 
=={{header|REXX}}==
Line 6,436 ⟶ 7,547:
::* &nbsp; optimized for speed (only one random number/mutation)
::* &nbsp; supports an alphabet with lowercase letters and other letters and/or punctuation.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates an evolutionary algorithm (by using mutation). */
parse arg children MR seed . /*get optional arguments from the C.L. */
if children=='' | children=="," then children=10 /*# children produced each generation. */
Line 6,468 ⟶ 7,579:
else $= $ || substr(x , j , 1)
end /*j*/
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the following input: &nbsp; &nbsp; <tt> 20 &nbsp; 4% &nbsp; 11 </tt>}}
<pre>
Line 6,507 ⟶ 7,618:
<br>generating a random character &nbsp; ['''@.n'''] &nbsp; during mutation, &nbsp; thus making it slightly faster &nbsp; (about 10%),
<br>especially for a longer string and/or a low mutation rate.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates an evolutionary algorithm (by using mutation). */
parse arg children MR seed . /*get optional arguments from the C.L. */
if children=='' | children=="," then children=10 /*# children produced each generation. */
Line 6,546 ⟶ 7,657:
else $= $ || substr(x, m, 1)
end /*m*/
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; is the same as the previous version.}}
<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Evolutionary algorithm
 
Line 6,609 ⟶ 7,720:
next
return number(str)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 6,746 ⟶ 7,857:
 
{{trans|C}}
<langsyntaxhighlight lang="ruby">@target = "METHINKS IT IS LIKE A WEASEL"
Charset = [" ", *"A".."Z"]
COPIES = 100
Line 6,784 ⟶ 7,895:
parent = copies.max_by {|c| fitness(c)}
end
log(iteration, rate, parent)</langsyntaxhighlight>
 
{{out}}
Line 6,841 ⟶ 7,952:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">//! Author : Thibault Barbie
//!
//! A simple evolutionary algorithm written in Rust.
Line 6,941 ⟶ 8,052:
c => c as char,
}
}</langsyntaxhighlight>
{{out}}
<div style='height: 15em; overflow: scroll'><pre>
Line 6,976 ⟶ 8,087:
{{works with|Scala|2.8.1}}
 
<langsyntaxhighlight lang="scala">import scala.annotation.tailrec
 
case class LearnerParams(target:String,rate:Double,C:Int)
Line 7,012 ⟶ 8,123:
implicit val params = LearnerParams("METHINKS IT IS LIKE A WEASEL",0.01,100)
val initial = (1 to params.target.size) map(x => randchar) mkString
evolve(0,initial)</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 7,074 ⟶ 8,185:
(display (string-append "Found: " parent "\n")))
(display parent) (newline))
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const string: table is "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Line 7,138 ⟶ 8,249:
incr(generation);
until best = 0;
end func;</langsyntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">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;</syntaxhighlight>
{{out}}
<pre> 25 DSBHHVDSLFJFYAXRTZEAXBRDPATW
24 DSBHHMDSLFJ YAXRTZEAXBRDPATW
23 DSBHHMDSLFT YAXRTZEAXBRDJATW
20 DSBHHMDSLFT YJXRTZEAX WDJSTW
...
1 METHINKS IT IS LPKE A WEASEL
1 METHINKS IT IS LQKE A WEASEL
0 METHINKS IT IS LIKE A WEASEL</pre>
 
=={{header|SequenceL}}==
{{trans|C#}}
'''SequenceL Code:'''<br>
<langsyntaxhighlight lang="sequencel">import <Utilities/Sequence.sl>;
 
AllowedChars := " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Line 7,165 ⟶ 8,327:
fitnesses := Fitness(target, mutations);
in
mutations[firstIndexOf(fitnesses, vectorMax(fitnesses))];</langsyntaxhighlight>
 
'''C++ Driver Code:'''<br>
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <time.h>
#include "SL_Generated.h"
Line 7,217 ⟶ 8,379:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 7,304 ⟶ 8,466:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">define target = "METHINKS IT IS LIKE A WEASEL"
define mutate_chance = 0.08
define alphabet = [('A'..'Z')..., ' ']
Line 7,316 ⟶ 8,478:
parent != target;
parent = C.of{ mutate(parent) }.max_by(fitness)
) { printf("%6d: '%s'\n", i++, parent) }</langsyntaxhighlight>
 
=={{header|Sinclair ZX81 BASIC}}==
Requires at least 2k of RAM. Displaying everything while it's running (generation count, parent, children, and their fitness scores) slows it down somewhat; but it would be very slow anyway, and it's nice to be able to look in on it from time to time and see how the program's getting along.
<langsyntaxhighlight lang="basic"> 10 LET A$="ABCDEFGHIJKLMNOPQRSTUVWXYZ "
20 LET T$="METHINKS IT IS LIKE A WEASEL"
30 LET L=LEN T$
Line 7,362 ⟶ 8,524:
410 IF S$(K)=T$(K) THEN LET R=R+1
420 NEXT K
430 RETURN</langsyntaxhighlight>
{{out}}
<pre> 349
Line 7,380 ⟶ 8,542:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">String subclass: Mutant [
<shape: #character>
 
Line 7,426 ⟶ 8,588:
randomLetter
[^Letters at: (Random between: 1 and: Letters size)]
]</langsyntaxhighlight>
 
Use example:
<langsyntaxhighlight Smalltalklang="smalltalk">st> Mutant run: 2500 rate: 0.1
QJUUIQHYXEZORSXGJCAHEWACH KG
QJUUIQHYXEZORSXGJCAHEWWCMSKG
Line 7,449 ⟶ 8,611:
METHINKS IW IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL
Mutant</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 7,455 ⟶ 8,617:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">func evolve(
to target: String,
parent: inout String,
Line 7,509 ⟶ 8,671:
print("Gen 0: \(start) with fitness \(fitness(target: target, sentence: start))")
 
evolve(to: target, parent: &start, mutationRate: mutationRate, copies: 100)</langsyntaxhighlight>
 
{{out}}
Line 7,538 ⟶ 8,700:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
def alphabet: [' ABCDEFGHIJKLMNOPQRSTUVWXYZ'...];
def target: ['METHINKS IT IS LIKE A WEASEL'...];
Line 7,555 ⟶ 8,717:
 
sink evolve
@: {generation: 0"1", parent: $};
$@.parent -> #
when <{fitness: <=$target::length>}> do
Line 7,561 ⟶ 8,723:
otherwise
'Fitness $.fitness; at generation $@.generation;: "$.candidate...;"$#10;' -> !OUT::write
@.generation: $@.generation + 1"1";
1..$generationSize -> [$@.parent.candidate... -> \(
when <?(100 -> SYS::randomInt <..~$mutationPercent>)> do $randomCharacter!
Line 7,570 ⟶ 8,732:
 
[1..$target::length -> $randomCharacter] -> countFitness -> !evolve
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 7,589 ⟶ 8,751:
{{works with|Tcl|8.5}}
{{trans|Python}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# A function to select a random character from an argument string
Line 7,643 ⟶ 8,805:
}
puts ""
que</langsyntaxhighlight>
Produces this example output:
<pre>#100 , fitness 42.9%, 'GSTBIGFS ITLSS LMD NNJPESZL'
Line 7,655 ⟶ 8,817:
===Alternate Presentation===
This alternative presentation factors out all assumption of what constitutes a “fit” solution to the <code>fitness</code> command, which is itself just a binding of the <code>fitnessByEquality</code> procedure to a particular target. None of the rest of the code knows anything about what constitutes a solution (and only <code>mutate</code> and <code>fitness</code> really know much about the data being evolved).
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc tcl::mathfunc::randchar {} {
# A function to select a random character
Line 7,724 ⟶ 8,886:
}
 
evolve $initial</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
This is a bit of a stretch, since uBasic/4tH doesn't support strings. Hence, the array is used to store the data.
<syntaxhighlight lang="text">T = 0 ' Address of target
L = 28 ' Length of string
P = T + L ' Address of parent
Line 7,835 ⟶ 8,997:
 
Proc _MutateDNA (P/L, P, 100) ' Now mutate the parent DNA
Return</langsyntaxhighlight>
{{out}}
<pre>ZACXCLONTNTEAMJXYYFEP QQMDTA
Line 7,873 ⟶ 9,035:
takes about 500 iterations give or take 100.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 7,892 ⟶ 9,054:
#cast %s
 
main = evolve parent</langsyntaxhighlight>
output:
<pre>
Line 7,899 ⟶ 9,061:
 
=={{header|UTFool}}==
<syntaxhighlight lang="utfool">
<lang UTFool>
···
http://rosettacode.org/wiki/Evolutionary_algorithm
Line 7,944 ⟶ 9,106:
generation◥
System.out.println "Target reached by generation #⸨generation⸩"
</syntaxhighlight>
</lang>
 
=={{header|vbscript}}==
<langsyntaxhighlight lang="vbscript">
'This is the string we want to "evolve" to. Any string of any length will
'do as long as it consists only of upper case letters and spaces.
Line 8,045 ⟶ 9,207:
Private Function Random ( lower , upper )
Random = Int((upper - lower + 1) * Rnd + lower)
End Function</langsyntaxhighlight>
 
Example output:
Line 8,078 ⟶ 9,240:
=={{header|Visual Basic}}==
Adapted from BBC Basic Code in this page. One diference from BBC Basic code is that in this code mutations are always good
<syntaxhighlight lang="visual basic">
<lang Visual Basic>
 
 
Line 8,141 ⟶ 9,303:
FNfitness = F / Len(Text)
End Function
</syntaxhighlight>
</lang>
 
Example output:
Line 8,171 ⟶ 9,333:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import rand
import rand.seed
const target = "METHINKS IT IS LIKE A WEASEL".bytes()
const set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".bytes()
 
 
fn initialize() []u8 {
rand.seed(seed.time_seed_array(2))
mut parent := []u8{len: target.len}
for i in 0..parent.len {
parent[i] = set[rand.intn(set.len) or {0}]
}
return parent
}
// fitness: 0 is perfect fit. greater numbers indicate worse fit.
fn fitness(a []u8) int {
mut h := 0
// (hamming distance)
for i, tc in target {
if a[i] != tc {
h++
}
}
return h
}
// set m to mutation of p, with each character of p mutated with probability r
fn mutate(p []u8, mut m []u8, r f64) {
for i, ch in p {
if rand.f64() < r {
m[i] = set[rand.intn(set.len) or {0}]
} else {
m[i] = ch
}
}
}
fn main() {
c := 20 // number of times to copy and mutate parent
mut parent := initialize()
mut copies := [][]u8{len: c, init: []u8{len: parent.len}}
println(parent.bytestr())
for best := fitness(parent); best > 0; {
for mut cp in copies {
mutate(parent, mut cp, .05)
}
for cp in copies {
fm := fitness(cp)
if fm < best {
best = fm
parent = cp.clone()
println(parent.bytestr())
}
}
}
}</syntaxhighlight>
{{out}}
<pre>Same as Go entry</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Option explicit
 
Function rand(l,u) rand= Int((u-l+1)*Rnd+l): End Function
 
Function fitness(i)
Dim d,j
d=0
For j=1 To lmod
If Mid(model,j,1)=Mid(cpy(i),j,1) Then d=d+1
Next
fitness=d
End Function
 
Sub mutate(i)
Dim j
cpy(i)=""
For j=1 To lmod
If Rnd<mut Then
cpy(i)=cpy(i)& Chr(rand(lb,ub))
Else
cpy(i)=cpy(i)& Mid(cpy(0),j,1)
End If
Next
End sub
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
 
Dim model,lmod,ub,lb,c,cpy,fit,best,i,d,mut,cnt
model="METHINKS IT IS LIKE A WEASEL"
model=Replace(model," ","@")
lmod=Len(model)
Randomize Timer
ub=Asc("Z")
lb=Asc("@")
c=10
mut=.05
best=0
ReDim cpy(c)
 
 
For i=0 To lmod-1
cpy(best)=cpy(best)& chr(rand(lb,ub))
Next
best=0
cnt=0
do
cpy(0)=cpy(best)
fit=0
For i=1 To c
mutate(i)
d=fitness(i)
If d>fit Then fit=d:best=i
Next
cnt=cnt+1
If (fit=lmod) Or ((cnt mod 10)=0) Then print cnt &" " & fit & " "& Replace (cpy(best),"@"," ")
Loop While fit <>lmod
</syntaxhighlight>
{{out}}
<small>
<pre>
 
10 3 EATZ FMSHTCSEARSNKQBKI CJHXU
20 4 EETZGALSQTMREARSCKQBKIVQJHXA
30 6 METZ NLSQYMXO RSCKUBKLVQJHZA
40 8 METZ NWSQYMCO RSCKUTJVEETSM
50 10 METZ NWSQYTCO KHIKUTPVEEQSHH
60 10 METMKNWAEITCOIYAIKUTPVUEQSTC
70 11 METMKNWSEITCXIIJIKDXPVUEQSTE
80 13 METMLNWSEITCXI PIKDXPVWEWSTE
90 16 METMHNWSUITTXK LIKDXDVWEWSEL
....
1920 23 METHINKS ITNGS LIKZ AIWEASTL
1930 23 METHINKSMITVQS LIKE ANWEASDL
1940 24 METHINKSMITVQS LIKE AQWEASEL
1950 24 METHINKSZITVQS LIKE ADWEASEL
1960 24 METHINKSCITVOS LIKE ADWEASEL
1970 25 METHINKSTITVOS LIKE A WEASEL
1980 25 METHINKSZITJFS LIKE A WEASEL
1990 25 MFTHINKSZIT NS LIKE A WEASEL
2000 25 MFTHINKSZIT OS LIKE A WEASEL
2010 26 MITHINKSZIT IS LIKE A WEASEL
2020 26 MITHINKSZIT IS LIKE A WEASEL
2030 26 MITHINKSSIT IS LIKE A WEASEL
2040 26 MITHINKSSIT IS LIKE A WEASEL
2050 27 MQTHINKS IT IS LIKE A WEASEL
2058 28 METHINKS IT IS LIKE A WEASEL
</pre>
</small>
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var target = "METHINKS IT IS LIKE A WEASEL"
Line 8,212 ⟶ 9,533:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 8,248 ⟶ 9,569:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic code declarations
string 0; \use zero-terminated convention (instead of MSb)
 
Line 8,316 ⟶ 9,637:
Iter:= Iter+1;
until Best = 0;
]</langsyntaxhighlight>
 
Example output:
Line 8,336 ⟶ 9,657:
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">const target = "METHINKS IT IS LIKE A WEASEL";
const C = 100; // Number of children in each generation.
const P = 0.05; // Mutation probability.
Line 8,349 ⟶ 9,670:
.reduce(fcn(a,b){ if(fitness(a)<fitness(b)) a else b });
println("Gen %2d, dist=%2d: %s".fmt(gen+=1, fitness(parent), parent));
}while(parent != target);</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits