Dirty
Dirty

Reputation: 55

Array help for genetic algorithm

So i'm building a genetic algorithm and basically to start with i'm creating a population of individuals and each individual has 8 genes in an array that are random selected as being a 0 or a 1. However when i create the population and output the array of each of the individual genes i do not get the expected output, i only get 28 1's or 0's whereas i should have 64. Can anyone help? Many Thanks.

Main class:

package geneticalgorithm;


public class GeneticAlgorithm {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
final int P = 20;
final int N = 8;
int count = 0; 
Random rand = new Random();

   Individual[] population = new Individual[P];


    for (int i = 0; i < P; i++){


        population[i] = new Individual(); //Generates a population of P individuals and gives each one unique genes
        population[i].generateGenes();
        population[i].fitness = 0;
    }

    for (int i = 0; i < P; i++){
        for (int j = 0; j < N; j++){
            if (population[i].genes[j] == 1 ){
                population[i].fitness++;

            }
        }    
    }  

    for (int i = 0; i < 8 ; i++){
     for (int j = 0; j < i; j++){


         count++;

        System.out.print(population[i].genes[j]);
     if ((count % N) == 0){
         System.out.println("");
     }
    }



    }
}}

Individual Class:

package geneticalgorithm;

import java.util.Random;



public class Individual {
private final int P = 20;
private final int N = 8;
int fitness;

int[] genes = new int[N];
private Object rand;

Individual() {
}

public void generateGenes(){

    Random rand = new Random();
    for(int i=0; i < N; ++i) {
        this.setGenes(i, (rand.nextInt(2)));
    }

}

public Individual(int[] genes){
    this.genes = genes;

}

public int[] getGenes() {
    return genes;
}

public void setGenes(int index, int genes) {
    this.genes[index] = genes;
}





}

Upvotes: 1

Views: 216

Answers (1)

sve
sve

Reputation: 4356

For printing the individuals in the population You have the loops:

for (int i = 0; i < 8 ; i++){
     for (int j = 0; j < i; j++){
         ...     
         System.out.print(population[i].genes[j]);
         ...
     } 
}

You are not going over all population member and not over all genes of each individual. Instead, you should have:

for (int i = 0; i < P; i++){
    for (int j = 0; j < N; j++){
        System.out.print(population[i].genes[j]);
    }
    System.out.println();
 }  

Upvotes: 1

Related Questions