I'm making a genetic algorithm that deals with evolving an array of chars into "Hello World". The problem is whenever I initialize a Chromosome object and call the generateChromosome method, all the chromosomes of "test" population remains the same? 
public class Chromosome{
   private static int defaultLength = 11;
   private static char []genes = new char[defaultLength]; <--- this remains the same for each object :/
   //Generates a random char chromosome
   public void generateChromosome(){
      char []newGene =  new char[defaultLength];
      for(int x = 0; x<size(); x++){
         char gene = (char)(32+Math.round(96*Math.random()));
         newGene[x] = gene;
      }
      genes = newGene;
   }
   //Returns a specific gene in the chromosome
   public char getGene(int index){
     return genes[index];
   }
   public char[] getChromosome(){
      return genes;
   }
   public void setGene(char value, int index){
   genes[index] = value;
   }
   public static  void setDefaultLength(int amount){
      defaultLength = amount;
   }
   public static int getDefaultLength(){
      return defaultLength;
   }
   public int size(){
      return genes.length;
   }
   @Override
   public String toString(){
      String geneString = "";
      for(int x= 0; x<genes.length; x++){
         geneString += genes[x];
      }
      return geneString;
   }
}
                That's because your variables are static, i.e. class variables. They will be the same in each instantiation of your class.
If you want an instance variable, remove the static keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With