CDE
This commit is contained in:
parent
518da4a923
commit
764da6cbbb
6144 changed files with 83610 additions and 11 deletions
33
Task/Evolutionary-algorithm/D/evolutionary-algorithm-1.d
Normal file
33
Task/Evolutionary-algorithm/D/evolutionary-algorithm-1.d
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import std.stdio, std.random, std.algorithm, std.range, std.ascii;
|
||||
|
||||
void evolve(string target, double prob=0.05, int C=100) {
|
||||
auto chars = uppercase ~ " ";
|
||||
char rndCh() { return chars[uniform(0, $)]; }
|
||||
void mutate(char[] parent, char[] child) {
|
||||
foreach (i, ref c; child)
|
||||
c = uniform(0.0, 1.0) < prob ? rndCh() : parent[i];
|
||||
}
|
||||
int fitness(char[] subject, string target) {
|
||||
return count!q{ a[0] != a[1] }(zip(subject, target));
|
||||
}
|
||||
auto parent= map!(i => rndCh())(target).array();
|
||||
auto best = parent.dup;
|
||||
auto child = new char[target.length];
|
||||
int currDist = fitness(parent, target);
|
||||
for (int gen; currDist > 0; gen++) {
|
||||
foreach (_; 0 .. C) {
|
||||
mutate(parent, child);
|
||||
int dist = fitness(child, target);
|
||||
if (dist < currDist) {
|
||||
currDist = dist;
|
||||
best[] = child[];
|
||||
}
|
||||
}
|
||||
parent = best;
|
||||
writefln("Generation %2s, dist=%2s: %s", gen, currDist, best);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
evolve("METHINKS IT IS LIKE A WEASEL");
|
||||
}
|
||||
19
Task/Evolutionary-algorithm/D/evolutionary-algorithm-2.d
Normal file
19
Task/Evolutionary-algorithm/D/evolutionary-algorithm-2.d
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import std.stdio, std.random, std.algorithm, std.range;
|
||||
|
||||
enum target = "METHINKS IT IS LIKE A WEASEL"d;
|
||||
enum C = 100; // Number of children in each generation.
|
||||
enum P = 0.05; // Mutation probability.
|
||||
auto alphabet = " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"d.dup;
|
||||
const fitness = (dchar[] s) => count!"a[0] != a[1]"(zip(s, target));
|
||||
const rndc = () => alphabet[uniform(0, $)];
|
||||
const mutate = (dchar[] s) =>
|
||||
s.map!(a => uniform(0., 1.) < P ? rndc() : a)().array();
|
||||
|
||||
void main() {
|
||||
auto parent = target.length.iota().map!(_ => rndc())().array();
|
||||
for (int gen = 1; parent != target; gen++) {
|
||||
auto offs = parent.repeat(C).map!mutate().array();
|
||||
parent = offs.minPos!((a, b) => fitness(a) < fitness(b))()[0];
|
||||
writefln("Gen %2d, dist=%2d: %s", gen, fitness(parent), parent);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue