示例#1
0
        private void Init(int numItems)
        {
            Started    = false;
            Generation = 0;

            // Create the sack items
            ExternalItems = new List <SackItem>();
            do
            {
                SackItem item = new SackItem(GAUtils.RandInt(0, 100), GAUtils.RandInt(0, 10));
                if (!ExternalItems.Any(i => i.Weight == item.Weight))
                {
                    ExternalItems.Add(item);
                }
            } while (ExternalItems.Count < numItems);

            int geneCombinations = numItems;
            int chromosoneLength = geneCombinations * 1; // 1 genes per chromosone (item in or out)

            // initialize the GA
            Algorithm = new GeneticAlgorithm <KnapsackGenome>(
                GeneticAlgorithm <KnapsackGenome> .DefaultCrossoverRate,
                GeneticAlgorithm <KnapsackGenome> .DefaultMutationRate,
                GeneticAlgorithm <KnapsackGenome> .DefaultPopulationSize,
                chromosoneLength,
                geneCombinations);

            // grab the genomes
            GenomePopulation = Algorithm.GrabGenomes();
        }
示例#2
0
        /// <summary>
        /// Takes 2 parent gene vectors, selects a midpoint and then swaps the ends
        /// of each genome creating 2 new genomes which are stored in baby1 and baby2
        /// </summary>
        /// <param name="other"></param>
        /// <param name="baby1"></param>
        /// <param name="baby2"></param>
        public void CrossOver(Genome <TMainModel, TCombinationModel> other, Genome <TMainModel, TCombinationModel> baby1, Genome <TMainModel, TCombinationModel> baby2)
        {
            // just return parents as offspring dependent on the rate
            // or if parents are the same
            if ((GAUtils.RandDouble() > _settings.CrossoverRate) || (this == other))
            {
                baby1.Genes = this.Genes;
                baby2.Genes = other.Genes;
                return;
            }

            if (baby1.Genes.Count <= 1 || baby2.Genes.Count <= 1)
            {
                baby1.Genes = this.Genes;
                baby2.Genes = other.Genes;
                return;
            }


            // determine a crossover point
            int crossOverPoint = GAUtils.RandInt(0, this.Genes.Count - 1); // = 29

            for (int i = 0; i < this.Genes.Count; i++)
            {
                var crossed = Genes[i].Cross(other.Genes[i], i < crossOverPoint);
                baby1.Genes.Add(crossed[0]);
                baby2.Genes.Add(crossed[1]);
            }
        }