// Genetic Ant Algorithm // Carl E. Bredlau // from Koza, _Genetic Programming_, MIT Press // programmed modeled after sga. Thanks to the author. package geneticAnt; public class Chromosome implements Cloneable { // Chromosome consists of Genes // Ant Actions public static final int MOVE = Gene.MOVE; public static final int LEFT = Gene.LEFT; public static final int RIGHT = Gene.RIGHT; public static final int NOP = Gene.NOP; int numState = 0; Gene[] mem; // For generation. NOTE: I don't clone the classes. IntRandom randAction; IntRandom randState; IntRandom randGene; public Chromosome(int states) { // we need two times states: one for state with food // and one without this.numState = states; randAction = new IntRandom(NOP+1); randState = new IntRandom(numState); randGene = new IntRandom(2*numState); mem = new Gene[2*numState]; for (int i = 0; i < 2*numState; i++){ mem[i] = new Gene(); //Init with random mem[i].state = randState.nextInt(); mem[i].action = randAction.nextInt(); } } public static String actionToDisplay(int action) { String str = null; switch(action) { case MOVE : str = "Move "; break; case LEFT : str = "Left "; break; case RIGHT: str = "Right"; break; case NOP : str = "NOP "; break; } return str; } public void show() { // show contents... System.out.println("State/Food : NextState Action"); for (int i = 0; i < 2*numState; i += 2) { System.out.println(i/2 + " N : " + mem[i].state + " " + actionToDisplay(mem[i].action) ); System.out.println(" Y : " + mem[i+1].state + " " + actionToDisplay(mem[i+1].action) ); } } protected Object clone() { Chromosome chr; try { chr = (Chromosome) super.clone(); chr.mem = new Gene[mem.length]; // access error... (Gene []) mem.clone(); //Unfortunately both mem's genes point to the same objects, so... for (int i = 0; i < chr.mem.length; i++) chr.mem[i] = (Gene) mem[i].clone(); // this.mem[4].state=2222; chr.mem[5].state=3333; // test clone } catch (CloneNotSupportedException e) { // cannot happen so throw new InternalError(e.toString()); } return chr; } public static void main(String args[]) { // Show a chormosome Chromosome chr = new Chromosome(6); Chromosome chr2 = (Chromosome) chr.clone(); chr.mem[3].state=100; chr2.mem[0].state = 1000; // test clone chr.show(); System.out.println("**********"); chr2.show(); } }