Exemple #1
0
 /// <summary>
 /// Returns the fitness of the gene
 /// </summary>
 /// <returns></returns>
 public int GetFitness()
 {
     if (fitness == 0)
     {
         fitness = FitnessCalculator.GetFitness(this);
     }
     return(fitness);
 }
        /**
         * Constructs a new population.
         * @param size The size of the population.
         * @param initialise True, if the population will be initialised.
         */
        public Population(FitnessCalculator fitnessCalculator, int size, int bitSize, int genotypeLength, int groupSize, bool initialise = false)
        {
            candidateSolutions     = new CandidateSolution[size];
            this.fitnessCalculator = fitnessCalculator;
            this.groupSize         = groupSize;

            if (initialise)
            {
                for (int i = 0; i < candidateSolutions.Length; i++)
                {
                    CandidateSolution candidateSolution = new CandidateSolution(fitnessCalculator, bitSize, genotypeLength, groupSize);
                    candidateSolution.GenerateIndividual();
                    candidateSolutions[i] = candidateSolution;
                }
            }
        }
        void RunGA()
        {
            FitnessCalculator.SetSolution("1111000000000001111000000000000000000000000000000000000000001111");

            Population pop = new Population(6, true);

            int epoch = 0;

            while (pop.GetFittest().GetFitness() < FitnessCalculator.GetMaxFitness())
            {
                epoch++;
                pop = Algorithm.EvolvePopulation(pop);
                System.Console.WriteLine("Generation: " + epoch + " Fittest: " + pop.GetFittest().GetFitness());
                System.Console.WriteLine(pop.GetFittest());
            }
            System.Console.WriteLine("Solution found");
            System.Console.WriteLine("Generation: " + epoch);
            System.Console.WriteLine("Genes:");
            System.Console.WriteLine(pop.GetFittest());
        }