September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,65 +1,68 @@
#import system.
#import system'routines.
#import extensions.
import system'routines.
import extensions.
#symbol Target = "METHINKS IT IS LIKE A WEASEL".
#symbol AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ".
#symbol C = 100.
#symbol P = 0.05r.
#symbol rnd = randomGenerator.
const Target = "METHINKS IT IS LIKE A WEASEL".
const AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ".
#symbol randomChar
= AllowedCharacters @ (rnd nextInt:(AllowedCharacters length)).
const C = 100.
const P = 0.05r.
#class(extension) evoHelper
rnd = randomGenerator.
randomChar
= AllowedCharacters[rnd nextInt(AllowedCharacters length)].
extension evoHelper
{
#method randomString
= 0 repeat &till:self &each:x [ randomChar ] summarize:(String new) literal.
randomString
= 0 till:self repeat(:x)( randomChar ); summarize:(String new); literal.
#method fitness &of:s
= self zip:s &into:(:a:b)[ (a == b)iif:1:0 ] summarize:(Integer new) int.
fitnessOf:s
= self zip:s by(:a:b)( (a == b)iif(1,0) ); summarize(Integer new); int.
#method mutate : p
= self select &each: ch [ (rnd nextReal <= p) iif:randomChar:ch ] summarize:(String new) literal.
mutate : p
= self selectBy(:ch)( (rnd nextReal <= p) iif(randomChar,ch) ); summarize(String new); literal.
}
#class EvoAlgorithm :: Enumerator
class EvoAlgorithm :: Enumerator
{
#field theTarget.
#field theCurrent.
#field theVariantCount.
object theTarget.
object theCurrent.
object theVariantCount.
#constructor new : s &of:count
constructor new : s of:count
[
theTarget := s.
theVariantCount := count int.
]
#method get = theCurrent.
get = theCurrent.
#method next
next
[
($nil == theCurrent)
? [ theCurrent := theTarget length randomString. ^ true. ].
if ($nil == theCurrent)
[ theCurrent := theTarget length; randomString. ^ true ].
(theTarget == theCurrent)
? [ ^ false. ].
if (theTarget == theCurrent)
[ ^ false ].
#var variants := Array new:theVariantCount set &every:(&index:x) [ theCurrent mutate:P ].
var variants := Array new:theVariantCount; populate(:x)( theCurrent mutate:P ).
theCurrent := variants array sort:(:a:b) [ a fitness &of:Target > b fitness &of:Target ] getAt:0.
theCurrent := variants array; sort(:a:b)( a fitnessOf:Target > b fitnessOf:Target ); getAt:0.
^ true.
]
}
#symbol program =
program =
[
#var attempt := Integer new.
EvoAlgorithm new:Target &of:C run &each:current
var attempt := Integer new.
EvoAlgorithm new:Target of:C; forEach(:current)
[
console
writeLiteral:"#":(attempt += 1) &paddingLeft:10
writeLine:" ":current:" fitness: ":(current fitness &of:Target).
printPaddingLeft(10,"#",attempt append:1);
printLine(" ",current," fitness: ",current fitnessOf:Target).
].
console readChar.
].