Пример #1
0
        /**
         * Template method controlling search. It returns the best individual in the
         * specified population, according to the specified FITNESS-FN and goal
         * test.
         *
         * @param initPopulation
         *            a set of individuals
         * @param fitnessFn
         *            a function that measures the fitness of an individual
         * @param goalTest
         *            test determines whether a given individual is fit enough to
         *            return. Can be used in subclasses to implement additional
         *            termination criteria, e.g. maximum number of iterations.
         * @param maxTimeMilliseconds
         *            the maximum time in milliseconds that the algorithm is to run
         *            for (approximate). Only used if > 0L.
         * @return the best individual in the specified population, according to the
         *         specified FITNESS-FN and goal test.
         */
        // function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual
        // inputs: population, a set of individuals
        // FITNESS-FN, a function that measures the fitness of an individual
        public virtual Individual <A> geneticAlgorithm(ICollection <Individual <A> > initPopulation, IFitnessFunction <A> fitnessFn,
                                                       GoalTest <Individual <A> > goalTest, long maxTimeMilliseconds)
        {
            Individual <A> bestIndividual = null;

            // Create a local copy of the population to work with
            ICollection <Individual <A> > population = CollectionFactory.CreateQueue <Individual <A> >(initPopulation);

            // Validate the population and setup the instrumentation
            validatePopulation(population);
            updateMetrics(population, 0, 0L);

            IStopWatch sw = CommonFactory.CreateStopWatch();

            // repeat
            int itCount = 0;

            do
            {
                population     = nextGeneration(population, fitnessFn);
                bestIndividual = retrieveBestIndividual(population, fitnessFn);

                updateMetrics(population, ++itCount, sw.GetElapsedMilliseconds());

                // until some individual is fit enough, or enough time has elapsed
                if (maxTimeMilliseconds > 0L && sw.GetElapsedMilliseconds() > maxTimeMilliseconds)
                {
                    break;
                }
                if (currIsCancelled)
                {
                    break;
                }
            } while (!goalTest(bestIndividual));

            notifyProgressTrackers(itCount, population);
            // return the best individual in population, according to FITNESS-FN
            return(bestIndividual);
        }