With my GA's crossover method, I keep getting an ArrayOutOfBounds Exception while concatenating the mother's second half to the father's first half. The ArrayList's are all the same size. Why does my mother keep trying to access the 10th element in my list of objects? MyPair is an object with a random direction and random number of steps.
We are currently learning this topic in my A.I. class, so I'm not an expert in GA's yet. Any additional commentary on my crossover algorithm is welcomed.
public static class Chromosome{
public ArrayList<MyPair> pairs;
private double x, y;
public double cost;
public Chromosome(){
this.pairs = new ArrayList<MyPair>();
this.x = 100.0; this.y = 100.0;
// not sure if I should do this or not
for(int numPairs = 0; numPairs < 10; numPairs++)
this.addToChromosome();
}
public void addToChromosome(){
MyPair myPair = new MyPair();
this.pairs.add(myPair);
}
public ArrayList<MyPair> getPairsList(){
return this.pairs;
}
public Chromosome crossOver(Chromosome father, Chromosome mother){
Chromosome replacement = new Chromosome();
int pos1 = r.nextInt(father.getPairsList().size());
while(pos1 >= 10)
pos1 = r.nextInt(father.getPairsList().size());
for(int i = 0; i < pos1; i++){
MyPair tempPair = father.getPairsList().get(i);
replacement.getPairsList().set(i, tempPair);
}
for(int i = pos1; i < mother.getPairsList().size() - 1; i++){
MyPair tempPair = mother.getPairsList().get(i);
// ArrayList keeps trying to set out of bounds here
replacement.getPairsList().set(i, tempPair);
}
return replacement;
}