import java.util.Random; import java.util.Arrays; /** Driver.java - a simple example illustrating the mechanics of genetic algorithms * We seek to create an "optimal" list of 10 numbers. * But only the fitness function knows what constraint we are aiming for! * * The program will create 20 individuals. * We also need to set the number of iterations (next generations). */ public class Driver { public static final int ITERS = 300; public static final double MUTATION_THRESHOLD = 0.001; public static void main(String [] args) { // Initialize the population. Population p = new Population(); // A loop for the generations. for (int i = 0; i < ITERS; ++i) { // Calculate the fitness of each individual. for (int j = 0; j < Population.SIZE; ++j) p.individual[j].findFitness(); // Output System.out.printf("Iteration %d, Population = \n%s\n", i, p.toString()); // Ready to create a new generation. // Sort the population by fitness. // p is the population object, whose "individual" attribute is the array. Arrays.sort(p.individual, new FitnessComparator()); // For i = 1 to n, select 2 parents to mate based on high fitness. // Choose them randomly from the upper 1/2 of the population. Random gen = new Random(System.nanoTime()); Individual [] newGeneration = new Individual[Population.SIZE]; for (int j = 0; j < Population.SIZE; ++j) { int parent1 = gen.nextInt(Population.SIZE / 2); int parent2 = gen.nextInt(Population.SIZE / 2); // Create a child individual by randomly selecting an allele from // either parent. Individual child = new Individual(); for (int gene = 0; gene < Individual.SIZE; ++gene) { // Flip a coin, a number either 1 or 2. int coin = gen.nextInt(2) + 1; // Based on the coin flip, set child's allele to the parent's. // Be careful with the syntax. if (coin == 1) child.a[gene] = p.individual[parent1].a[gene]; else child.a[gene] = p.individual[parent2].a[gene]; } // Allow for a mutation in the child. double prob = gen.nextDouble(); if (prob < MUTATION_THRESHOLD) { // Arbitrarily change the first gene to a random allele value. child.a[0] = Individual.randomAlleleValue(); } // Put the child into the new generation. newGeneration[j] = child; } // We now have a new generation. Replace the old one. for (int j = 0; j < Population.SIZE; ++j) p.individual[j] = newGeneration[j]; } } }