-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcsharp.cs
93 lines (79 loc) · 2.96 KB
/
csharp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
namespace Weasel
{
using System;
using System.Collections.Generic;
using System.Linq;
class Individual
{
public string Lookslike { get; private set; }
public Individual(string lookslike)
{
Lookslike = lookslike;
}
public IEnumerable<Individual> ReproduceChildren(double mutationRate, int numberOfChildren, string alphabet)
{
return Enumerable.Range(0, numberOfChildren).Select(i => ReproduceChild(mutationRate, alphabet));
}
private Individual ReproduceChild(double mutationRate, string alphabet)
{
var newLookslike = Lookslike.Select(c => WeaselWorld.MutateCharacter(c, mutationRate, alphabet));
return new Individual(new string(newLookslike.ToArray()));
}
}
class WeaselWorld
{
private static readonly Random Random = new Random();
private readonly string _alphabet;
private readonly string _goal;
public WeaselWorld(string alphabet, string goal)
{
_alphabet = alphabet;
_goal = goal;
}
private Individual CreateFirstSire()
{
var firstSireLookslike =
Enumerable.Range(0, _goal.Length)
.Select(i => _alphabet[Random.Next(_alphabet.Length)]);
return new Individual(new string(firstSireLookslike.ToArray()));
}
private int CalculateAlikeness(string child)
{
//Read more about Zip in LINQ
return child
.Zip(_goal, (childCharacter, goalCharacter) => childCharacter == goalCharacter)
.Count(c => c);
}
internal static char MutateCharacter(char character, double mutationRate, string alphabet)
{
return Random.NextDouble() < mutationRate ? alphabet[Random.Next(alphabet.Length)] : character;
}
private Individual GetFittest(IEnumerable<Individual> children)
{
return children.OrderByDescending(c => CalculateAlikeness(c.Lookslike)).First();
}
public void CreateWeasel(double mutationRate, int numberOfChildren)
{
var sire = CreateFirstSire();
Console.WriteLine(sire.Lookslike);
var generations = 1;
while (!sire.Lookslike.Equals(_goal))
{
var children = sire.ReproduceChildren(mutationRate, numberOfChildren, _alphabet);
sire = GetFittest(children);
Console.WriteLine(generations++);
Console.WriteLine(sire.Lookslike);
}
Console.WriteLine("Finished at generation " + generations);
}
}
class Program
{
static void Main(string[] args)
{
var weaselWorld = new WeaselWorld("ABCDEFGHIJKLMNOPQRSTUVWXYZ ", "METHINKS IT IS LIKE A WEASEL");
weaselWorld.CreateWeasel(0.04d, 100);
Console.ReadKey();
}
}
}