⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 binarygeneticalgorithm.cs

📁 Generalization of a Simple Genetic Algorithm (GA)
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;

namespace GeneticAlgorithmLib
{
    public abstract class BinaryGeneticAlgorithm : GeneticAlgorithmBase
    {
        private double m_ChanceOfInfect;
        private double m_ChanceOfMutate;

        #region Constructors / Destructors
        public BinaryGeneticAlgorithm(double ChanceOfInfect, double ChanceOfMutate)
            : base(2)
        {
            m_ChanceOfInfect = ChanceOfInfect;
            m_ChanceOfMutate = ChanceOfMutate;
            this.m_NumberOfSelectees = 2;
        }
        #endregion

        #region Overrides
        public override void ChooseWinners(List<IGenotype> Potentials, out List<IGenotype> Winners, out List<IGenotype> Losers)
        {
            Winners = (List<IGenotype>)new List<IGenotype>();
            Losers = (List<IGenotype>)new List<IGenotype>();
            IGenotype gWinner, gLoser;
            this.ChooseWinners(Potentials[0], Potentials[1], out gWinner, out gLoser);
            ((List<IGenotype>)Winners).Add(gWinner);
            ((List<IGenotype>)Losers).Add(gLoser);
        }
        protected override void Recombine(List<IGenotype> Winners, List<IGenotype> Losers)
        {
            IGenotype Winner = Winners[0],
                Loser = Losers[0];
            Random r = new Random();
            for (int i = 0; i < Loser.Genes.Count; i++)
            {
                double rand = r.NextDouble();
                if (rand < this.m_ChanceOfInfect)
                {
                    Loser.Genes[i].SetGene(Winner.Genes[i].Value);
                }
            }
        }
        protected override void Mutate(List<IGenotype> Losers)
        {
            IGenotype Loser = Losers[0];
            Random r = new Random();
            for (int i = 0; i < Loser.Genes.Count; i++)
            {
                double rand = r.NextDouble();
                if (rand < this.m_ChanceOfMutate)
                {
                    Loser.Genes[i].SetGene(Loser.Genes[i].Value == EGene.On
                        ? EGene.Off
                        : EGene.On);
                }
            }
        }
        protected override bool Evaluate(List<IGenotype> Genes)
        {
            return Evaluate(Genes[0]);
        }
        #endregion

        #region Abstract
        protected abstract void ChooseWinners(IGenotype First, IGenotype Second, out IGenotype gWinner, out IGenotype gLoser);
        protected abstract bool Evaluate(IGenotype Genes);
        #endregion
    }   
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -