Exemplo n.º 1
0
        public GeneticAlgorithmTest()
        {
            bool found = false;
            int target = 1547881;
            generation = new Chromosome[PopulationSize];
            for (int i = 0; i < PopulationSize; i++)
            {
                generation[i] = new Chromosome();
                generation[i].ComputeFitness(target);
            }

            while (!found)
            {
                double totalFitness = 0.0f;
                foreach (var chromosome in generation)
                {
                    totalFitness += chromosome.Fitness;
                    if (chromosome.Fitness == 999)
                    {
                        Console.WriteLine("------------------");
                        Console.WriteLine("Result is {0}={1}", chromosome.Decode(chromosome.EncodedChromosome), target);
                        Console.WriteLine("------------------");
                        Console.WriteLine("Press any key to continue...");
                        Console.ReadKey();

                        found = true;
                        break;
                    }
                }
                Console.WriteLine("Total fitness {0}", totalFitness);
                Chromosome[] newPopulation = new Chromosome[PopulationSize];
                int newSize = 0;
                do
                {
                    Chromosome parent1 = this.Roulette(totalFitness, this.generation);
                    Chromosome parent2 = this.Roulette(totalFitness, this.generation);
                    Chromosome child = parent1.Mutate(parent2);
                    child.ComputeFitness(target);
                    newPopulation[newSize++] = child;
                } while (newSize < PopulationSize);
                generation = newPopulation;
            }
        }
Exemplo n.º 2
0
        public Chromosome Mutate(Chromosome chromosome)
        {
            int chromosomeLength = this.EncodedChromosome.Length;
            if (chromosome.EncodedChromosome.Length != chromosomeLength)
            {
                throw new ApplicationException("Chromosomes can't make babies");
            }

            string childChromosome = this.EncodedChromosome;
            int crossoverBeginIndex = Random.Next(chromosomeLength);
            var array = childChromosome.ToCharArray();

            if (this.GetRandomNumber() < CrossoverRate)
            {
                for (int i = crossoverBeginIndex; i < chromosomeLength; ++i)
                {
                    array[i] = chromosome.EncodedChromosome[i];
                }
            }

            for (int i = crossoverBeginIndex; i < chromosomeLength; ++i)
            {
                if (this.GetRandomNumber() < MutationRate)
                {
                    array[i] = array[i] == '0' ? '1' : '0';
                }
            }

            var child = new Chromosome(new string(array));
            return child;
        }