遗传算法通用写法C#

遗传算法是通过模拟生物进化而进行数据寻优的一种进化算法。主要过程是初始种群的产生,选择,交叉,变异,循环迭代,直至出现最优解。本程序两个主要类,种群类与个体类。定义进化策略接口,计算适应度策略接口。进化策略接口实现三个行为,交叉,变异,选择,其中,进化策略接口可以加上自己的实现。大致实现如下:

//
//class Population
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace SGA.SingleGA
{
     /*
     群体类,实现了种群初始化,有交叉,变异行为,选择等行为。同时统计种群的平均适应度,最大适应度,适应度之和。
     */
    public class Population : CollectionBase,ICloneable,IDisposable
    {
        private IGeneticStrategy _iGeneticStrategy;
       
        public Population(IGeneticStrategy iGeneticStrategy) { this._iGeneticStrategy = iGeneticStrategy; }
        public Population() { }
        public void Init(int iMax)
        {
            Random rd = new Random();
            for (int i = 0; i < iMax; i++)
            {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < 22; j++)
                {
                    sb.Append(rd.Next(0,2));
                }
                this.List.Add(new Individual(sb.ToString()));
            }
        }
        public double MaxFitness
        {
            get
            {
                double dmax = double.MinValue;
                for (int i = 0; i < List.Count; i++)
                {
                    if ((List[i] as Individual).Fitness > dmax) dmax = (List[i] as Individual).Fitness;
                }
                return dmax;
            }          
        }
        public double AverageFitness
        {
            get
            {
                return SumFitness / List.Count;
            }
        }
        public double SumFitness
        {
            get
            {
                double dSum = 0;
                for (int i = 0; i < List.Count; i++)
                {
                    dSum += (List[i] as Individual).Fitness;
                }
                return dSum;
            }
        }
        public IGeneticStrategy GeneticStrategy
        {
            get { return this._iGeneticStrategy; }
            set { this._iGeneticStrategy = value; }
        }
        public Population Select()
        {
            if (_iGeneticStrategy == null) return null;
            return _iGeneticStrategy.Select(this);
        }

        public void Crossover()
        {
            if (_iGeneticStrategy == null) return;
            _iGeneticStrategy.Crossover(this);
        }
        public void Mutation()
        {
            if (_iGeneticStrategy == null) return;
            _iGeneticStrategy.Mutation(this);
        }

        public Individual this[int index]
        {
            get { return (Individual)this.List[index]; }
            set { this.List[index] = value; }
        }
        public void Add(Individual ind)
        {
            this.List.Add(ind);
        }
        public int Indexof(Individual ind)
        {
            return this.List.IndexOf(ind);
        }
        public void Print()
        {
            for (int i = 0; i < List.Count; i++)
            {
                Console.WriteLine("第{0}个体fit={2} {1}", i.ToString(), (List[i] as Individual).Variable.ToString(), (List[i] as Individual).Fitness);
            }
        }
      

        #region ICloneable 成员

        public object Clone()
        {
            Population pop = new Population(this.GeneticStrategy);
            for (int i = 0; i < this.List.Count; i++)
                pop.List.Add(this.List[i]);
            return pop;
        }

        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            _iGeneticStrategy = null;
        }

        #endregion
    }
}


//
//Individual
//

using System;
using System.Collections.Generic;
using System.Text;

namespace SGA.SingleGA
{
    public class Individual : ICloneable
    {
        private string _gene;
        private double _fitness = double.MinValue;
        public static IFitness _calFit = new OneDFitness();
        public string Gene
        {
            get { return _gene; }
            set
            {
                _gene = value;
                _fitness = _calFit.Fitness(Variable);
            }
        }
        public double Fitness
        {
            get { return _fitness; }
        }
        public double Variable
        {
            get { return Coder.ToReal(_gene, -1.0, 2.0); }
        }
        public Individual()
        {
        }
        public Individual(string sGene)
        {
            Gene = sGene;
        }
        public Individual(string sGene,IFitness calFit)
        {
            _calFit = calFit;
            this.Gene = sGene;
        }
        //public IFitness CalFit
        //{
        //    get { return this._calFit; }
        //    set
        //    {
        //        this._calFit = value;
        //        _fitness = _calFit.Fitness(Coder.ToReal(_gene, -1.0, 2.0));
        //    }
        //}

        public int ToMetrication()
        {
            return Convert.ToInt32(Gene, 2);
        }

        public static int operator * (Individual ind1,Individual ind2)
        {
            Random rd = new Random();
            int iStart = rd.Next(0, ind1.Gene.Length-2);
            int iLast = rd.Next(iStart+1,ind1.Gene.Length-1);
            while (ind1.Gene.Substring(iStart, iLast - iStart) == ind2.Gene.Substring(iStart, iLast - iStart))
            {
                iStart = rd.Next(0, ind1.Gene.Length - 2);
                iLast = rd.Next(iStart + 1, ind1.Gene.Length - 1);
            }

            StringBuilder sbGene1 = new StringBuilder();
            sbGene1.Append(ind1.Gene.Substring(0, iStart));
            sbGene1.Append(ind2.Gene.Substring(iStart, iLast-iStart));
            sbGene1.Append(ind1.Gene.Substring(iLast));
            StringBuilder sbGene2 = new StringBuilder();
            sbGene2.Append(ind2.Gene.Substring(0, iStart));
            sbGene2.Append(ind1.Gene.Substring(iStart,iLast-iStart));
            sbGene2.Append(ind2.Gene.Substring(iLast));
            ind1.Gene = sbGene1.ToString();
            ind2.Gene = sbGene2.ToString();

            return iLast - iStart;
        }
        public int Crossover(Individual ind)
        {
            return this * ind;
        }
        public int Mutation()
        {
            Random rd = new Random();
            int iPos = rd.Next(0, this.Gene.Length-1);
            StringBuilder sb = new StringBuilder(this.Gene);
            sb[iPos] = sb[iPos] == '0' ? '1' : '0';
            this.Gene = sb.ToString();
            return iPos;
        }


       

        public override string ToString()
        {
            return this.Gene;
        }
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        #region ICloneable 成员

        public object Clone()
        {
            return new Individual(this.Gene);
        }

        #endregion
    }
}

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dijkstra最短路径算法的矩阵写法主要有两种方式:邻接矩阵和距离矩阵。 邻接矩阵写法: 首先,定义一个二维矩阵adj[n][n]表示图中每个节点i与节点j之间是否有连接,若有则adj[i][j]=1,否则adj[i][j]=0。此外,再定义一个一维矩阵dis[n],表示源点s到每个节点i的最短距离。 然后,初始化dis[n]数组,将源点s到每个节点i的初始距离都赋值为无穷大,除了源点s到自身的距离为0。接下来,遍历整张图,每次从未被访问的节点中选择一个距离源点s最近的节点u,更新其邻接的节点v的最短距离。具体地,如果dis[v]>dis[u]+adj[u][v],则更新dis[v]=dis[u]+adj[u][v]。 最后,遍历完整张图后,dis数组中的所有元素即为源点s到所有节点的最短距离。 距离矩阵写法: 首先,定义一个二维矩阵dist[n][n]表示图中每个节点i与节点j之间的距离。然后,同样定义一个一维矩阵dis[n],表示源点s到每个节点i的最短距离。 接下来,初始化dis[n]数组,将源点s到每个节点i的初始距离都赋值为dist[s][i],除了源点s到自身的距离为0。然后,遍历整张图,每次从未被访问的节点中选择一个距离源点s最近的节点u,更新其邻接的节点v的最短距离。具体地,如果dis[v]>dis[u]+dist[u][v],则更新dis[v]=dis[u]+dist[u][v]。 最后,遍历完整张图后,dis数组中的所有元素即为源点s到所有节点的最短距离。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值