4

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;
   }
}
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73

5 Answers5

3

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.

ktm5124
  • 11,861
  • 21
  • 74
  • 119
2

static means one per class (not one per instance). Remove the static

private char[] genes = new char[defaultLength];

and your genes becomes an instance field.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

static members belong to the class - they are shared across all its instances. You should define genes as an instance member by removing the static keyword:

public class Chromosome{
   private static int defaultLength = 11; // should probably be final, BTW
   private char[] genes = new char[defaultLength]; // not static!
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Since you are using static keyword in genes it is not an instance variable. Therefore though you assigned the created array to it, there will be only one instance through out the application.

You cam remove the static keyword and uses instance gene variable.

1

Make genes as instance variable by removing static keyword. Because,

1) static means one per class

2) instance means one per instance

For more information on static, see https://stackoverflow.com/a/413904/2127125

Community
  • 1
  • 1
TSKSwamy
  • 225
  • 2
  • 21