Skip to content

Instantly share code, notes, and snippets.

@charlesj
Created June 15, 2012 22:51
Show Gist options
  • Save charlesj/2939107 to your computer and use it in GitHub Desktop.
Save charlesj/2939107 to your computer and use it in GitHub Desktop.
Breeder
public class Breeder
{
public double ChanceOfMutation { get; private set; }
public Couple Couple { get; private set; }
public Breeder(double chanceOfMutation, Couple couple)
{
Couple = couple;
ChanceOfMutation = chanceOfMutation;
}
public Genotype GetChild()
{
var genotype = new Genotype();
for (int i = 0; i < Couple.Mother.Genes.Count; i++ )
{
var mutate = ShouldMutate();
if (i < Couple.Father.Genes.Count && Couple.Father.Genes[i] != null && (Couple.Father.Genes[i] != Couple.Mother.Genes[i] || mutate))
{
if(mutate)
{
Mutate(genotype);
}
else
{
genotype.Genes.Add(RandomNumberSource.GetNext(1) == 1
? new Gene (Couple.Mother.Genes[i].Value )
: new Gene ( Couple.Father.Genes[i].Value ));
}
}
else if (i < Couple.Father.Genes.Count)
{
genotype.Genes.Add(new Gene (Couple.Mother.Genes[i].Value ));
}
else
{
genotype.Genes.Add(new Gene(Couple.Mother.Genes[i].Value ));
}
}
if (Couple.Father.Genes.Count > Couple.Mother.Genes.Count)
{
for (int i = Couple.Father.Genes.Count - Couple.Mother.Genes.Count; i < Couple.Father.Genes.Count; i++)
{
if( ShouldMutate() )
{
Mutate(genotype);
}
else
{
genotype.Genes.Add(new Gene (Couple.Father.Genes[i].Value ));
}
}
}
return genotype;
}
private bool ShouldMutate()
{
double chance = Math.Round(ChanceOfMutation, 3);
int intChance = Convert.ToInt32(chance * 1000);
int value = RandomNumberSource.GetNext(100000);
if (value < intChance)
{
return true;
}
return false;
}
private void Mutate(Genotype genotype)
{
int next = RandomNumberSource.GetNext(2);
if (next == 2 || next == 1)
{
AddRandomGene(genotype);
}
else if (next == 2)
{
AddRandomGene(genotype);
}
}
private void AddRandomGene(Genotype genotype)
{
genotype.Genes.Add(Gene.GetRandomGene());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment