Add tasks for all the new languages
This commit is contained in:
parent
9dc3c2bb62
commit
bba7bfd280
13208 changed files with 134745 additions and 0 deletions
94
Task/Evolutionary-algorithm/8th/evolutionary-algorithm.8th
Normal file
94
Task/Evolutionary-algorithm/8th/evolutionary-algorithm.8th
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
\ RosettaCode challenge http://rosettacode.org/wiki/Evolutionary_algorithm
|
||||
\ Responding to the criticism that the implementation was too directed, this
|
||||
\ version does a completely random selection of chars to mutate
|
||||
|
||||
var gen
|
||||
\ Convert a string of valid chars into an array of char-strings:
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ " null s:/ var, valid-chars
|
||||
|
||||
\ How many mutations each generation will handle; the larger, the slower each
|
||||
\ generation but the fewer generations required:
|
||||
300 var, #mutations
|
||||
23 var, mutability
|
||||
|
||||
: get-random-char
|
||||
valid-chars @
|
||||
27 rand-pcg n:abs swap n:mod
|
||||
a:@ nip ;
|
||||
|
||||
: mutate-string \ s -- s'
|
||||
(
|
||||
rand-pcg mutability @ n:mod not if
|
||||
drop get-random-char
|
||||
then
|
||||
) s:map ;
|
||||
|
||||
: mutate \ s n -- a
|
||||
\ iterate 'n' times over the initial string, mutating it each time
|
||||
\ save the original string, as the best of the previous generation:
|
||||
>r [] over a:push swap
|
||||
(
|
||||
tuck mutate-string
|
||||
a:push swap
|
||||
) r> times drop ;
|
||||
|
||||
\ compute Hamming distance of two strings:
|
||||
: hamming \ s1 s2 -- n
|
||||
0 >r
|
||||
s:len n:1-
|
||||
(
|
||||
2 pick over s:@ nip
|
||||
2 pick rot s:@ nip
|
||||
n:- n:abs r> n:+ >r
|
||||
) 0 rot loop
|
||||
2drop r> ;
|
||||
|
||||
var best
|
||||
: fitness-check \ s a -- s t
|
||||
10000 >r
|
||||
-1 best !
|
||||
(
|
||||
\ ix s ix s'
|
||||
2 pick hamming
|
||||
r@
|
||||
over n:> if
|
||||
rdrop >r
|
||||
best !
|
||||
else
|
||||
2drop
|
||||
then
|
||||
)
|
||||
a:each
|
||||
rdrop best @ a:@ nip ;
|
||||
|
||||
|
||||
: add-random-char \ s -- s'
|
||||
get-random-char s:+ ;
|
||||
|
||||
\ take the target and make a random string of the same length
|
||||
: initial-string \ s -- s
|
||||
s:len "" swap
|
||||
' add-random-char
|
||||
swap times ;
|
||||
|
||||
: done? \ s1 s2 -- s1 s2 | bye
|
||||
2dup s:= if
|
||||
"Done in " . gen @ . " generations" . cr ;;;
|
||||
then ;
|
||||
|
||||
: setup-random
|
||||
rand rand rand-pcg-seed ;
|
||||
|
||||
: evolve
|
||||
1 gen n:+!
|
||||
\ create an array of #mutations strings mutated from the random string, drop the random
|
||||
#mutations @ mutate
|
||||
\ iterate over the array and pick the closest fit:
|
||||
fitness-check
|
||||
\ show this generation's best match:
|
||||
dup . cr
|
||||
\ check for end condition and continue if not done:
|
||||
done? evolve ;
|
||||
|
||||
"METHINKS IT IS LIKE A WEASEL"
|
||||
setup-random initial-string evolve bye
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import ceylon.random {
|
||||
|
||||
DefaultRandom
|
||||
}
|
||||
|
||||
shared void run() {
|
||||
|
||||
value mutationRate = 0.05;
|
||||
value childrenPerGeneration = 100;
|
||||
value target = "METHINKS IT IS LIKE A WEASEL";
|
||||
value alphabet = {' ', *('A'..'Z')};
|
||||
value random = DefaultRandom();
|
||||
|
||||
value randomLetter => random.nextElement(alphabet);
|
||||
|
||||
function fitness(String a, String b) =>
|
||||
count {for([c1, c2] in zipPairs(a, b)) c1 == c2};
|
||||
|
||||
function mutate(String string) =>
|
||||
String {
|
||||
for(letter in string)
|
||||
if(random.nextFloat() < mutationRate)
|
||||
then randomLetter
|
||||
else letter
|
||||
};
|
||||
|
||||
function makeCopies(String string) =>
|
||||
{for(i in 1..childrenPerGeneration) mutate(string)};
|
||||
|
||||
function chooseFittest(String+ children) =>
|
||||
children
|
||||
.map((String element) => element->fitness(element, target))
|
||||
.max(increasingItem)
|
||||
.key;
|
||||
|
||||
variable value parent = String {for(i in 1..target.size) randomLetter};
|
||||
variable value generationCount = 0;
|
||||
function display() => print("``generationCount``: ``parent``");
|
||||
|
||||
display();
|
||||
while(parent != target) {
|
||||
parent = chooseFittest(parent, *makeCopies(parent));
|
||||
generationCount++;
|
||||
display();
|
||||
}
|
||||
|
||||
print("mutated into target in ``generationCount`` generations!");
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
(require 'sequences)
|
||||
(define ALPHABET (list->vector ["A" .. "Z"] ))
|
||||
(vector-push ALPHABET " ")
|
||||
|
||||
(define (fitness source target) ;; score >=0, best is 0
|
||||
(for/sum [(s source)(t target)]
|
||||
(if (= s t) 0 1)))
|
||||
|
||||
(define (mutate source rate)
|
||||
(for/string [(s source)]
|
||||
(if (< (random) rate) [ALPHABET (random 27)] s)))
|
||||
|
||||
(define (select parent target rate copies (copy) (score))
|
||||
(define best (fitness parent target))
|
||||
(define selected parent)
|
||||
(for [(i copies)]
|
||||
(set! copy (mutate parent rate))
|
||||
(set! score (fitness copy target))
|
||||
(when (< score best)
|
||||
(set! selected copy)
|
||||
(set! best score)))
|
||||
selected )
|
||||
|
||||
(define MUTATION_RATE 0.05) ;; 5% chances to change
|
||||
(define COPIES 100)
|
||||
(define TARGET "METHINKS IT IS LIKE A WEASEL")
|
||||
|
||||
(define (task (rate MUTATION_RATE) (copies COPIES) (target TARGET) (score))
|
||||
(define parent ;; random source
|
||||
(for/string
|
||||
[(i (string-length target))] [ALPHABET (random 27)]))
|
||||
|
||||
(for [(i (in-naturals))]
|
||||
(set! score (fitness parent target))
|
||||
(writeln i parent 'score score)
|
||||
#:break (zero? score)
|
||||
(set! parent (select parent target rate copies))
|
||||
))
|
||||
34
Task/Evolutionary-algorithm/Nim/evolutionary-algorithm.nim
Normal file
34
Task/Evolutionary-algorithm/Nim/evolutionary-algorithm.nim
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import math, os
|
||||
randomize()
|
||||
|
||||
const
|
||||
target = "METHINKS IT IS LIKE A WEASEL"
|
||||
alphabet = " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"
|
||||
p = 0.05
|
||||
c = 100
|
||||
|
||||
proc random(a: string): char = a[random(a.low..a.len)]
|
||||
|
||||
proc negFitness(trial): int =
|
||||
for i in 0 .. <trial.len:
|
||||
if target[i] != trial[i]: inc result
|
||||
|
||||
proc mutate(parent): string =
|
||||
result = ""
|
||||
for c in parent: result.add if random(1.0) < p: random(alphabet) else: c
|
||||
|
||||
var parent = ""
|
||||
for i in 1..target.len: parent.add random(alphabet)
|
||||
|
||||
var i = 0
|
||||
while parent != target:
|
||||
var copies = newSeq[string](c)
|
||||
for i in 0 .. <copies.len: copies[i] = mutate(parent)
|
||||
|
||||
var best = copies[0]
|
||||
for i in 1 .. <copies.len:
|
||||
if negFitness(copies[i]) < negFitness(best): best = copies[i]
|
||||
parent = best
|
||||
|
||||
echo i, " ", parent
|
||||
inc i
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
200 Constant new: C
|
||||
5 Constant new: RATE
|
||||
|
||||
: randChar // -- c
|
||||
27 rand dup 27 == ifTrue: [ drop ' ' ] else: [ 'A' + 1- ] ;
|
||||
|
||||
: fitness(a b -- n)
|
||||
a b zipWith(#==) sum ;
|
||||
|
||||
: mutate(s -- s')
|
||||
s map(#[ 100 rand RATE <= ifTrue: [ drop randChar ] ]) charsAsString ;
|
||||
|
||||
: evolve(target)
|
||||
| parent |
|
||||
ListBuffer init(target size, #randChar) charsAsString ->parent
|
||||
|
||||
1 while ( parent target <> ) [
|
||||
ListBuffer init(C, #[ parent mutate ]) dup add(parent)
|
||||
maxFor(#[ target fitness ]) dup ->parent . dup println 1+
|
||||
] drop ;
|
||||
36
Task/Evolutionary-algorithm/Phix/evolutionary-algorithm.phix
Normal file
36
Task/Evolutionary-algorithm/Phix/evolutionary-algorithm.phix
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
constant target = "METHINKS IT IS LIKE A WEASEL",
|
||||
AZS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
|
||||
C = 5000, -- children in each generation
|
||||
P = 15 -- probability of mutation (1 in 15)
|
||||
|
||||
function fitness(string sample, string target)
|
||||
return sum(sq_eq(sample,target))
|
||||
end function
|
||||
|
||||
function mutate(string s, integer n)
|
||||
for i=1 to length(s) do
|
||||
if rand(n)=1 then
|
||||
s[i] = AZS[rand(length(AZS))]
|
||||
end if
|
||||
end for
|
||||
return s
|
||||
end function
|
||||
|
||||
string parent = mutate(target,1) -- (mutate with 100% probability)
|
||||
sequence samples = repeat(0,C)
|
||||
integer gen = 0, best, fit, best_fit = fitness(parent,target)
|
||||
while parent!=target do
|
||||
printf(1,"Generation%3d: %s, fitness %3.2f%%\n", {gen, parent, (best_fit/length(target))*100})
|
||||
best_fit = -1
|
||||
for i=1 to C do
|
||||
samples[i] = mutate(parent, P)
|
||||
fit = fitness(samples[i], target)
|
||||
if fit > best_fit then
|
||||
best_fit = fit
|
||||
best = i
|
||||
end if
|
||||
end for
|
||||
parent = samples[best]
|
||||
gen += 1
|
||||
end while
|
||||
printf(1,"Finally, \"%s\"\n",{parent})
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
use "random"
|
||||
|
||||
actor Main
|
||||
let _env: Env
|
||||
let _rand: MT = MT // Mersenne Twister
|
||||
let _target: String = "METHINKS IT IS LIKE A WEASEL"
|
||||
let _possibilities: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
||||
let _c: U16 = 100 // number of spawn per generation
|
||||
let _min_mutate_rate: F64 = 0.09
|
||||
let _perfect_fitness: USize = _target.size()
|
||||
var _parent: String = ""
|
||||
|
||||
new create(env: Env) =>
|
||||
_env = env
|
||||
_parent = mutate(_target, 1.0)
|
||||
var iter: U64 = 0
|
||||
while not _target.eq(_parent) do
|
||||
let rate: F64 = new_mutate_rate()
|
||||
iter = iter + 1
|
||||
if (iter % 100) == 0 then
|
||||
_env.out.write(iter.string() + ": " + _parent)
|
||||
_env.out.write(", fitness: " + fitness(_parent).string())
|
||||
_env.out.print(", rate: " + rate.string())
|
||||
end
|
||||
var best_spawn = ""
|
||||
var best_fit: USize = 0
|
||||
var i: U16 = 0
|
||||
while i < _c do
|
||||
let spawn = mutate(_parent, rate)
|
||||
let spawn_fitness = fitness(spawn)
|
||||
if spawn_fitness > best_fit then
|
||||
best_spawn = spawn
|
||||
best_fit = spawn_fitness
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
if best_fit > fitness(_parent) then
|
||||
_parent = best_spawn
|
||||
end
|
||||
end
|
||||
_env.out.print(_parent + ", " + iter.string())
|
||||
|
||||
fun fitness(trial: String): USize =>
|
||||
var ret_val: USize = 0
|
||||
var i: USize = 0
|
||||
while i < trial.size() do
|
||||
try
|
||||
if trial(i) == _target(i) then
|
||||
ret_val = ret_val + 1
|
||||
end
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
ret_val
|
||||
|
||||
fun new_mutate_rate(): F64 =>
|
||||
let perfect_fit = _perfect_fitness.f64()
|
||||
((perfect_fit - fitness(_parent).f64()) / perfect_fit) * (1.0 - _min_mutate_rate)
|
||||
|
||||
fun ref mutate(parent: String box, rate: F64): String =>
|
||||
var ret_val = recover trn String end
|
||||
for char in parent.values() do
|
||||
let rnd_real: F64 = _rand.real()
|
||||
if rnd_real <= rate then
|
||||
let rnd_int: U64 = _rand.int(_possibilities.size().u64())
|
||||
try
|
||||
ret_val.push(_possibilities(rnd_int.usize()))
|
||||
end
|
||||
else
|
||||
ret_val.push(char)
|
||||
end
|
||||
end
|
||||
consume ret_val
|
||||
115
Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony
Normal file
115
Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
use "random"
|
||||
use "collections"
|
||||
|
||||
class CreationFactory
|
||||
let _desired: String
|
||||
|
||||
new create(d: String) =>
|
||||
_desired = d
|
||||
|
||||
fun apply(c: String): Creation =>
|
||||
Creation(c, _fitness(c))
|
||||
|
||||
fun _fitness(s: String): USize =>
|
||||
var f = USize(0)
|
||||
for i in Range(0, s.size()) do
|
||||
try
|
||||
if s(i) == _desired(i) then
|
||||
f = f +1
|
||||
end
|
||||
end
|
||||
end
|
||||
f
|
||||
|
||||
class val Creation
|
||||
let string: String
|
||||
let fitness: USize
|
||||
|
||||
new val create(s: String = "", f: USize = 0) =>
|
||||
string = s
|
||||
fitness = f
|
||||
|
||||
class Mutator
|
||||
embed _rand: MT = MT
|
||||
let _possibilities: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
||||
let _cf: CreationFactory
|
||||
|
||||
new create(cf: CreationFactory) =>
|
||||
_cf = cf
|
||||
|
||||
fun ref apply(parent: Creation, rate: F64): Creation =>
|
||||
let ns = _new_string(parent.string, rate)
|
||||
_cf(ns)
|
||||
|
||||
fun ref _new_string(parent: String, rate: F64): String =>
|
||||
var mutated = recover String(parent.size()) end
|
||||
for char in parent.values() do
|
||||
mutated.push(_mutate_letter(char, rate))
|
||||
end
|
||||
consume mutated
|
||||
|
||||
fun ref _mutate_letter(current: U8, rate: F64): U8 =>
|
||||
if _rand.real() <= rate then
|
||||
_random_letter()
|
||||
else
|
||||
current
|
||||
end
|
||||
|
||||
fun ref _random_letter(): U8 =>
|
||||
let ln = _rand.int(_possibilities.size().u64()).usize()
|
||||
try _possibilities(ln) else ' ' end
|
||||
|
||||
class Generation
|
||||
let _size: USize
|
||||
let _desired: Creation
|
||||
let _mutator: Mutator
|
||||
|
||||
new create(size: USize = 100, desired: Creation, mutator: Mutator) =>
|
||||
_size = size
|
||||
_desired = desired
|
||||
_mutator = consume mutator
|
||||
|
||||
fun ref apply(parent: Creation): Creation =>
|
||||
var best = parent
|
||||
let mutation_rate = _mutation_rate(best)
|
||||
for i in Range(0, _size) do
|
||||
let candidate = _mutator(best, mutation_rate)
|
||||
if candidate.fitness > best.fitness then
|
||||
best = candidate
|
||||
end
|
||||
end
|
||||
best
|
||||
|
||||
fun _mutation_rate(best: Creation): F64 =>
|
||||
let min_mutate_rate: F64 = 0.09
|
||||
|
||||
let df = _desired.fitness.f64()
|
||||
let bf = best.fitness.f64()
|
||||
|
||||
((df - bf) / df) * (1.0 - min_mutate_rate)
|
||||
|
||||
actor Main
|
||||
new create(env: Env) =>
|
||||
let d = "METHINKS IT IS LIKE A WEASEL"
|
||||
let cf = CreationFactory(d)
|
||||
let desired = cf(d)
|
||||
let mutator = Mutator(cf)
|
||||
let start = mutator(desired, 1.0)
|
||||
let spawn_per_generation = USize(100)
|
||||
|
||||
var iterations = U64(0)
|
||||
var best = start
|
||||
|
||||
repeat
|
||||
best = Generation(spawn_per_generation, desired, mutator)(best)
|
||||
|
||||
iterations = iterations + 1
|
||||
if (iterations % 100) == 0 then
|
||||
env.out.print(
|
||||
iterations.string() + ": "
|
||||
+ best.string + ", fitness: " + best.fitness.string()
|
||||
)
|
||||
end
|
||||
until best.string == desired.string end
|
||||
|
||||
env.out.print(best.string + ", " + iterations.string())
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import <Utilities/Sequence.sl>;
|
||||
|
||||
AllowedChars := " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
initializeParent(randChars(1)) := AllowedChars[randChars];
|
||||
|
||||
Fitness(target(1), current(1)) :=
|
||||
let
|
||||
fit[i] := true when target[i] = current[i];
|
||||
in
|
||||
size(fit);
|
||||
|
||||
Mutate(letter(0), rate(0), randRate(0), randChar(0)) :=
|
||||
letter when randRate > rate
|
||||
else
|
||||
AllowedChars[randChar];
|
||||
|
||||
evolve(target(1), parent(1), C(0), P(0), rateRands(2), charRands(2)) :=
|
||||
let
|
||||
mutations[i] := Mutate(parent, P, rateRands[i], charRands[i]) foreach i within 1 ... C;
|
||||
fitnesses := Fitness(target, mutations);
|
||||
in
|
||||
mutations[firstIndexOf(fitnesses, vectorMax(fitnesses))];
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
#include <iostream>
|
||||
#include <time.h>
|
||||
#include "SL_Generated.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
int threads = 0;
|
||||
|
||||
char* targetString = "METHINKS IT IS LIKE A WEASEL";
|
||||
if(argc > 1) targetString = argv[1];
|
||||
int C = 100;
|
||||
if(argc > 2) C = atoi(argv[2]);
|
||||
SL_FLOAT P = 0.05;
|
||||
if(argc > 3) P = atof(argv[3]);
|
||||
int seed = time(NULL);
|
||||
if(argc > 4) seed = atoi(argv[4]);
|
||||
|
||||
int targetDims[] = {strlen(targetString), 0};
|
||||
Sequence<char> target((void*)targetString, targetDims);
|
||||
|
||||
sl_init(threads);
|
||||
|
||||
Sequence<char> parent;
|
||||
Sequence<char> newParent;
|
||||
Sequence<int> parentRands;
|
||||
sl_create(seed++, 1, 27, target.size(), threads, parentRands);
|
||||
sl_initializeParent(parentRands, threads, parent);
|
||||
|
||||
Sequence< Sequence<int> > charRands;
|
||||
Sequence< Sequence<SL_FLOAT> > rateRands;
|
||||
|
||||
cout << "Start:\t" << parent << endl;
|
||||
for(int i = 1; !(parent == target); i++)
|
||||
{
|
||||
sl_create(seed++, 1, 27, C, target.size(), threads, charRands);
|
||||
sl_create(seed++, 0.0, 1.0, C, target.size(), threads, rateRands);
|
||||
|
||||
sl_evolve(target, parent, C, P, rateRands, charRands, threads, newParent);
|
||||
parent = newParent;
|
||||
|
||||
cout << "#" << i << ":\t" << parent << endl;
|
||||
}
|
||||
cout << "End:\t" << parent << endl;
|
||||
|
||||
sl_done();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
define target = "METHINKS IT IS LIKE A WEASEL"
|
||||
define mutate_chance = 0.08
|
||||
define alphabet = [('A'..'Z')..., ' ']
|
||||
define C = 100
|
||||
|
||||
func fitness(str) { str.chars ~Z== target.chars -> count(true) }
|
||||
func mutate(str) { str.gsub(/(.)/, {|s1| 1.rand < mutate_chance ? alphabet.pick : s1 }) }
|
||||
|
||||
for (
|
||||
var (i, parent) = (0, alphabet.rand(target.len).join);
|
||||
parent != target;
|
||||
parent = C.of{ mutate(parent) }.max_by(fitness)
|
||||
) { printf("%6d: '%s'\n", i++, parent) }
|
||||
Loading…
Add table
Add a link
Reference in a new issue