/* GeneticAlgorithm.java * J Scott Cameron * * This class controls a population of Genotypes * for regenration using a Genetic Algorithm * * It uses the Java Reflection API so that * it is possible to change the fitness function * for new GA problems without having to touch this * class */ import java.lang.reflect.*; import java.util.*; import java.io.*; import Genotype; import GenotypeComparator; public class GeneticAlgorithm{ private Genotype population[];/* population of Genotypes */ private boolean crossover; /* boolean that control crossover */ private boolean mutation; /* boolean that controls mutation */ private int popSize; /* population size */ private int genotypeLength; /* length of a genotype */ private double mutationRate; /* rate at which mutations occur */ private String fitnessFunction; /* name of the fitness function */ private Random random; /* random object to be passed to genotypes */ private Object target; /* Object that contains fitness function */ private int sumFitness; /* sum of all the fitnesses in the population */ private int lowestFitness; /* the worst fitness found */ public GeneticAlgorithm() { } /* parameterized constructor * the only non-obvious components are "target" and "fitnessFunction" * this is the name of the fitness function and the an instance of * the object which contains it */ public GeneticAlgorithm(int genotypeLength, int popSize, boolean crossover, boolean mutation, double mutationRate, Object target, String fitnessFunction) { this.genotypeLength = genotypeLength; this.popSize = popSize; this.crossover = crossover; this.mutation = mutation; this.mutationRate = mutationRate; this.fitnessFunction = fitnessFunction; this.target = target; } /* initializes the population with random Genotypes */ public void initPopulation() { random = new Random(); population = new Genotype[popSize]; for(int i=0;i= x) { return population[i]; } } } return population[popSize-1]; } /* evaluates all the Genotypes in the population and sorts them*/ public void evaluatePopulation() { /* iterate trough all the genotypes... */ for(int i=0;i