// Put the unpacked gaLibrary folder in processing-###/libraries // The following line will include the library import ai.ga.*; PFont font; Sum sum; String solution = ""; String target = "target: 30"; void setup(){ size(400, 150); sum = new Sum(30); font = loadFont("ArialMT-30.vlw"); textFont(font, 30); } void draw(){ background(0); fill(255); text("Generations:" + sum.generation(), 30, 40); text(solution, 30, 80); text(target, 30, 120); if(sum.found()){ Chromosome temp = (Chromosome)sum.solutions().get(0); solution = "solution:" + sum.dnaToString(temp); } else{ sum.propagate(); } } void mousePressed(){ int rand = (int)random(10,40); sum = new Sum(rand); target = "target: "+rand; solution = ""; } class Sum extends GeneticAlgorithm{ // Variables specific to your task can go here int target; Sum(int target){ // The first line must be a call to GeneticAlgorithm's constructor // The constructor defines (dnaLength(), traitSize(), poolSize()) and initialises default variables // If you are using the method propagate() the poolSize must be a factor of 2 super(5, 10, 4); // Update your variables here // This is also the place to modify the GeneticAlgorithm's fields this.target = target; } // A method overriding scoreFitness must be defined. // Fitness in the GA is defined as a number that approaches // or equals zero. // In the following example the values in dna() are being added together to see if they match a target float scoreFitness(Chromosome o){ int total = 0; for(int i = 0; i < dnaLength(); i++){ if(o.dna()[i] < traitSize()){ total += o.dna()[i]; } } if(total == target){ return 0.0f; } return 1.0 / (target - total); } // If your dna() values are returning an index in a Vector of objects // or happen to be char values, you may want to put a decode() method here String dnaToString(Chromosome o){ int total = 0; StringBuffer answer = new StringBuffer(); for(int i = 0; i < dnaLength(); i++){ if(o.dna()[i] < traitSize()){ total += o.dna()[i]; answer.append(o.dna()[i]); if(i < dnaLength()-1){ answer.append('+'); } } } return answer.toString(); } }