September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -1,68 +1,76 @@
import system'routines.
import extensions.
import system'routines;
import extensions;
import extensions'text;
const Target = "METHINKS IT IS LIKE A WEASEL".
const AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ".
const string Target = "METHINKS IT IS LIKE A WEASEL";
const string AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const C = 100.
const P = 0.05r.
const int C = 100;
const real P = 0.05r;
rnd = randomGenerator.
rnd = randomGenerator;
randomChar
= AllowedCharacters[rnd nextInt(AllowedCharacters length)].
= AllowedCharacters[rnd.nextInt(AllowedCharacters.Length)];
extension evoHelper
{
randomString
= 0 till:self repeat(:x)( randomChar ); summarize:(String new); literal.
randomString()
= 0.repeatTill(self).selectBy:(x => randomChar).summarize(new StringWriter());
fitnessOf:s
= self zip:s by(:a:b)( (a == b)iif(1,0) ); summarize(Integer new); int.
fitnessOf(s)
= self.zipBy(s, (a,b => a==b ? 1 : 0)).summarize(new Integer()).toInt();
mutate : p
= self selectBy(:ch)( (rnd nextReal <= p) iif(randomChar,ch) ); summarize(String new); literal.
mutate(p)
= self.selectBy:(ch => rnd.nextReal() <= p ? randomChar : ch).summarize(new StringWriter());
}
class EvoAlgorithm :: Enumerator
class EvoAlgorithm : Enumerator
{
object theTarget.
object theCurrent.
object theVariantCount.
object theTarget;
object theCurrent;
object theVariantCount;
constructor new : s of:count
[
theTarget := s.
theVariantCount := count int.
]
constructor new:of(s,count)
{
theTarget := s;
theVariantCount := count.toInt();
}
get = theCurrent.
get() = theCurrent;
next
[
if ($nil == theCurrent)
[ theCurrent := theTarget length; randomString. ^ true ].
bool next()
{
if (nil == theCurrent)
{ theCurrent := theTarget.Length.randomString(); ^ true };
if (theTarget == theCurrent)
[ ^ false ].
{ ^ false };
var variants := Array new:theVariantCount; populate(:x)( theCurrent mutate:P ).
auto variants := Array.allocate(theVariantCount).populate:(x => theCurrent.mutate:P );
theCurrent := variants array; sort(:a:b)( a fitnessOf:Target > b fitnessOf:Target ); getAt:0.
theCurrent := variants.sort:(a,b => a.fitnessOf:Target > b.fitnessOf:Target ).at:0;
^ true.
]
^ true
}
reset()
{
theCurrent := nil
}
enumerable() => theTarget;
}
program =
[
var attempt := Integer new.
EvoAlgorithm new:Target of:C; forEach(:current)
[
public program()
{
var attempt := new Integer();
EvoAlgorithm.new:Target of:C.forEach:(current)
{
console
printPaddingLeft(10,"#",attempt append:1);
printLine(" ",current," fitness: ",current fitnessOf:Target).
].
.printPaddingLeft(10,"#",attempt.append(1))
.printLine(" ",current," fitness: ",current.fitnessOf(Target))
};
console readChar.
].
console.readChar()
}