Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 19, 2013 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4984761 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4984761 to your computer and use it in GitHub Desktop.
GA1: Genome class
namespace GeneticAlgorithm
{
public class Genome
{
static Random _random = new Random();
public static double MutationRate { get; set; }
public double Fitness { get; set; }
public int Length { get; private set; }
public double[] Genes { get; private set; }
public Genome(int length)
{
Length = length;
Genes = new double[length];
CreateGenes();
}
public Genome(int length, bool createGenes)
{
Length = length;
Genes = new double[length];
if (createGenes)
CreateGenes();
}
public Genome(ref double[] genes)
{
Length = genes.GetLength(0);
Genes = new double[Length];
for (int i = 0; i < Length; i++)
Genes[i] = genes[i];
}
private void CreateGenes()
{
// DateTime d = DateTime.UtcNow;
for (int i = 0; i < Length; i++)
Genes[i] = _random.NextDouble();
}
public void Crossover(ref Genome genome2, out Genome child1, out Genome child2)
{
int pos = (int)(_random.NextDouble() * (double)Length);
child1 = new Genome(Length, false);
child2 = new Genome(Length, false);
for (int i = 0; i < Length; i++)
{
if (i < pos)
{
child1.Genes[i] = Genes[i];
child2.Genes[i] = genome2.Genes[i];
}
else
{
child1.Genes[i] = genome2.Genes[i];
child2.Genes[i] = Genes[i];
}
}
}
public void Mutate()
{
for (int pos = 0; pos < Length; pos++)
{
if (_random.NextDouble() < MutationRate)
Genes[pos] = (Genes[pos] + _random.NextDouble()) / 2.0;
}
}
public void GetValues(ref double[] values)
{
for (int i = 0; i < Length; i++)
values[i] = Genes[i];
}
public override string ToString()
{
string result = "";
for (int i = 0; i < Length; i++)
{
result += string.Format("{0:F4}", Genes[i]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment