import java.util.*; public class GA { public static void main(String[] args) { new GA().doIt(Integer.parseInt(args[0])); } // Static info static char[] ltable = {'0','1','2','3','4','5','6','7','8','9','+','-','*','/'}; static int chromoLen = 5; static double crossRate = .7; static double mutRate = .001; static Random rand = new Random(); static int poolSize = 40; // Must be even private void doIt(int target) { int gen=0; // Create the pool ArrayList pool = new ArrayList(poolSize); ArrayList newPool = new ArrayList(pool.size()); // Generate unique cromosomes in the pool for (int x=0;x=0;x-=2) { // Select two members Chomosone n1 = selectMember(pool); Chomosone n2 = selectMember(pool); // Cross over and mutate n1.crossOver(n2); n1.mutate(); n2.mutate(); // Rescore the nodes n1.scoreChromo(target); n2.scoreChromo(target); // Check to see if either is the solution if (n1.total == target && n1.isValid()) { System.out.println("Generations: " + gen + " Solution: " + n1.decodeChromo()); return; } if (n2.total == target && n2.isValid()) { System.out.println("Generations: " + gen + " Solution: " + n2.decodeChromo()); return; } // Add to the new pool newPool.add(n1); newPool.add(n2); } // Add the newPool back to the old pool pool.addAll(newPool); } } //---- Chomosone Class ----- private Chomosone selectMember(ArrayList l) { // Get the total fitness double tot=0.0; for (int x=l.size()-1;x>=0;x--) { double score = ((Chomosone)l.get(x)).score; tot+=score; } double slice = tot*rand.nextDouble(); // Loop to find the node double ttot=0.0; for (int x=l.size()-1;x>=0;x--) { Chomosone node = (Chomosone)l.get(x); ttot+=node.score; if (ttot>=slice) { l.remove(x); return node; } } return (Chomosone)l.remove(l.size()-1); } // Genetic Algorithm Node private static class Chomosone { // The chromo StringBuffer chromo = new StringBuffer(chromoLen * 4); public StringBuffer decodeChromo = new StringBuffer(chromoLen * 4); public double score; public int total; // Constructor that generates a random public Chomosone(int target) { // Create the full buffer for(int y=0;y crossRate) return; // Generate a random position int pos = rand.nextInt(chromo.length()); // Swap all chars after that position for (int x=pos;x0 && ch=='0' && decodedString.charAt(x-1)=='/') return false; num = !num; } // Can't end in an operator if (!Character.isDigit(decodedString.charAt(decodedString.length()-1))) return false; return true; } } }