Source file unity-csharp/nature-of-code/genetic-algorithm-text/DNA.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: Minimal DNA container for a beginner Unity genetic algorithm
// Related pages: [[genetic-algorithms]], [[overview-unity-nature-of-code-examples]]
 
using UnityEngine;
 
public class DNA
{
    private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
 
    public char[] Genes { get; }
    public float Fitness { get; private set; }
 
    public DNA(int length)
    {
        Genes = new char[length];
        Randomise();
    }
 
    public string Text => new string(Genes);
 
    public void Randomise()
    {
        for (int i = 0; i < Genes.Length; i++)
            Genes[i] = Alphabet[Random.Range(0, Alphabet.Length)];
    }
 
    public void Evaluate(string target)
    {
        int matches = 0;
 
        for (int i = 0; i < Genes.Length; i++)
            if (Genes[i] == target[i])
                matches++;
 
        Fitness = (float)matches / target.Length;
    }
 
    public DNA Crossover(DNA other)
    {
        DNA child = new DNA(Genes.Length);
        int midpoint = Random.Range(0, Genes.Length);
 
        for (int i = 0; i < Genes.Length; i++)
            child.Genes[i] = i < midpoint ? Genes[i] : other.Genes[i];
 
        return child;
    }
 
    public void Mutate(float rate)
    {
        for (int i = 0; i < Genes.Length; i++)
            if (Random.value < rate)
                Genes[i] = Alphabet[Random.Range(0, Alphabet.Length)];
    }
}