Evolutionary algorithm: Difference between revisions

Add second solution for Smalltalk
(add UTFool solution)
(Add second solution for Smalltalk)
Line 6,579:
 
=={{header|Smalltalk}}==
===Version 1===
{{works with|GNU Smalltalk}}
<lang smalltalk>Object subclass: Evolution [
Line 6,696 ⟶ 6,697:
 
organism getEvolutionStatus displayNl.</lang>
 
===Version 2===
{{works with|Gnu Smalltalk}}
<lang smalltalk>
String subclass: Mutant [
<shape: #character>
 
Target := Mutant from: 'METHINKS IT IS LIKE A WEASEL'.
Letters := ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
 
Mutant class >> run: c rate: p
["Run Evolutionary algorighm, using c copies and mutate rate p."
| pool parent |
parent := self newRandom.
pool := Array new: c+1.
 
[parent displayNl.
parent = Target] whileFalse:
[1 to: c do: [:i | pool at: i put: (parent copy mutate: p)].
pool at: c+1 put: parent.
parent := pool fold: [:winner :each | winner fittest: each]]]
 
Mutant class >> newRandom
[^(self new: Target size)
initializeToRandom;
yourself]
 
initializeToRandom
[self keys do: [:i | self at: i put: self randomLetter]]
 
mutate: p
[self keys do:
[:i |
Random next <= p ifTrue: [self at: i put: self randomLetter]]]
 
fitness
[| score |
score := 0.
self with: Target do:
[:me :you |
me = you ifTrue: [score := score + 1]].
^score]
 
fittest: aMutant
[^self fitness > aMutant fitness
ifTrue: [self]
ifFalse: [aMutant]]
 
randomLetter
[^Letters at: (Random between: 1 and: Letters size)]
]
</lang>
 
Use example:
<lang Smalltalk>
st> Mutant run: 2500 rate: 0.1
QJUUIQHYXEZORSXGJCAHEWACH KG
QJUUIQHYXEZORSXGJCAHEWWCMSKG
QEUUIUHYXEZORSOGICAHYWWCSSKG
QETUIUHGXEZORS GICE YWWCSSEG
METUIUHSXOZORS OICE YWWCSSEG
METUIUHSXOZORS OICE Y WCSSEG
METUIUHSXOZMIS OIOE Y WCNSEG
METKIUKSTOFMIS LIOE Y WCNSEG
METKINKSTOFMIS LIKE E WCNSEG
METKINKSTOFMIS LIKE F WCNSEL
METHINKSTOF IS LIKE F WCNSEL
METHINKS OW IS LIKE F WCNSEL
METHINKS IW IS LIKE F WCNSEL
METHINKS IW IS LIKE C WCASEL
METHINKS IW IS LIKE C WCASEL
METHINKS IW IS LIKE A WCASEL
METHINKS IW IS LIKE A WCASEL
METHINKS IW IS LIKE A WEASEL
METHINKS IT IS LIKE A WEASEL
Mutant
</lang>
 
=={{header|Tcl}}==
Anonymous user