/* This is our class to describe the DNA, or the genotype, of a virtual organism. We're storing the DNA as a series of characters for this example. We need to include a few utility methods for working with our DNA: - Convert the DNA to a String - Determine the DNA's "fitness" - Mate the DNA with another DNA object - Mutate the DNA sequence */ class DNA { // Our genetic sequence char[] dna; // Create a new random series of DNA with a given length public DNA(int chars) { // create the dna array dna = new char[chars]; // fill the dna with random values for (int i = 0; i < chars; i++) { dna[i] = (char)random(0, 255); } } // Create a new DNA sequence from an existing array of characters public DNA(char[] basedna) { // just copy the dna sequence dna = (char[])basedna.clone(); } // Get the string representation of our dna public String toString() { return new String(dna); } // Determine the "fitness" of our DNA sequence. For this // example the fitness is based upon how closely our DNA // matches a target string public float getFitness(String target) { int score = 0; // Check each character, and record how many match the target string for (int i = 0; i < dna.length; i++) { if (dna[i] == target.charAt(i)) { score++; } } // our fitness is simply the ratio of matched characters to the total // number of characters in the string float fitness = (float)score / (float)target.length(); return fitness; } public char getDNAat(int index) { return dna[index]; } // Our mating function is based upon the idea of "crossover", in which // the child of two parent DNA sequences is a continuous portion of each // parent. A point within the string is choosen, and the part of the DNA // before the point comes from one parent, while the part after the point // comes from the other parent public DNA mate(DNA partner) { // create the array for the new child dna char[] childDNA = new char[dna.length]; // choose a crossover point int crossover = int(random(dna.length)); // now copy the dna from the appropriate parent for (int i = 0; i < childDNA.length; i++) { if (i > crossover) { childDNA[i] = dna[i]; } else { childDNA[i] = partner.getDNAat(i); } } // create the new DNA object DNA newDNA = new DNA(childDNA); return newDNA; } // Mutate our DNA based upon the probability of any given character in // the DNA changing. public void mutate(float chance) { for (int i = 0; i < dna.length; i++) { if (random(1) < chance) { dna[i] = (char)random(0, 255); } } } }