/* Our DNA class is fairly straight forward, but we're using an array of Vector3D objects instead of characters as our DNA. Otherwise the process is the same for mating and mutation. */ public class DNA { // our genetic sequence, an array of force vectors Vector3D[] dna; // Create our DNA with a set size, filled with random force vectors public DNA(int num) { dna = new Vector3D[num]; // fill in random dna for (int i = 0; i < num; i++) { dna[i] = new Vector3D(random(-1, 1), random(-1, 1), 0); dna[i].normalize(); } } // Create our DNA from previously constructed DNA sequence public DNA(Vector3D[] olddna) { // copy our dna dna = (Vector3D[])olddna.clone(); } // return a dna element from a specific position Vector3D getGene(int index) { return dna[index]; } /* Create genetic crossover between this DNA and a partner */ DNA mate(DNA partner) { // make a place to store the new DNA Vector3D[] childDNA = new Vector3D[dna.length]; // choose a crossover point int crossover = (int)random(dna.length); // take half from us and half from the other "parent" for (int i = 0; i < dna.length; i++) { if (i < crossover) { childDNA[i] = partner.getGene(i); } else { childDNA[i] = getGene(i); } } DNA child = new DNA(childDNA); return child; } /* Mutate our DNA */ void mutate(float rate) { for (int i = 0; i < dna.length; i++) { if (random(1) < rate) { dna[i] = new Vector3D(random(-1, 1), random(-1, 1), 0); dna[i].normalize(); } } } }