vendredi 8 avril 2016

Genetic algorithm, crossover

I initialized chromosome as vector (whose length is n) of zeros and ones with exactly k ones. After crossover, I want to get chromosome whose length in n with k ones. I try to delete and add ones, random. I don't get correct result.

' public Chromosome Crossover(Chromosome ch)
    {
        int k = 0;
        for (int i = 0; i < vector.Length; i++)
        {
            if (vector[i] == 1)
                k += 1;
        }
          Chromosome child = new Chromosome(vector.Length);
   for (int j=0; j < vector.Length / 2; j++)

            child.setGene(j, vector[j]);


        for (; j < vector.Length; j++)

            child.setGene(j, ch.getGene(j));



        Random rnd = new Random();


 int numOfOnes = child.getOnes();
        if (numOfOnes > k)
        {
            while (numOfOnes != k)
            {
                int p = rnd.Next(numOfOnes), position = 0;
                for (int i = 0; i < child.getChromosomeLenght(); i++)
                {
                    if (child.getGene(i) == 1)
                        position++;
                    if (position == p)
                    {
                        child.setGene(p, 0);
                        break;
                    }
                }
                numOfOnes--;
            }
        }
        else if (numOfOnes < k)
        {
            while (numOfOnes != k)
            {
                int p = rnd.Next(child.getChromosomeLenght() - numOfOnes),                           position = 0;
                for (int i = 0; i < child.getChromosomeLenght(); i++)
                {
                    if (child.getGene(i) == 0)
                        position++;
                    if (position == p)
                    {
                        child.setGene(p, 1);
                        break;
                    }
                }
                numOfOnes++;
            }

        }
                    return child

}

Where I made mistake?




Aucun commentaire:

Enregistrer un commentaire