binarygeneticalgorithm.cs

来自「Generalization of a Simple Genetic Algor」· CS 代码 · 共 73 行

CS
73
字号
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 + =
减小字号Ctrl + -
显示快捷键?