CSharp遗传算法求解背包问题
断断续续写了四天,感觉背包问题是最适合了解遗传算法的问题模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Bag
{ /// <summary>
/// 背包类
/// </summary>
public class Bag
{
public int Size { get; }
public Bag(int Size)
{
this.Size = Size;
}
}
/// <summary>
/// 货物类
/// </summary>
public class Goods
{
public int Weight { set; get; }
public int Value { set; get; }
/// <summary>
/// 这里随机生成货物属性
/// </summary>
public Goods()
{
this.Weight = APP.Rd.Next() % 200 + 10;
this.Value = APP.Rd.Next() % 1000 + 50;
}
}
/// <summary>
/// 测试结果,编号,总重与总价
/// </summary>
public class Total
{
public int Index { set; get; }
public long TotalWeight { set; get; }
public long TotalValue { get; set; }
public Total(int Index, long TotalWeight, long TotalValue)
{
this.Index = Index;
this.TotalWeight = TotalWeight;
this.TotalValue = TotalValue;
}
} public class Chromosome
{
private bool[] _GeneList = new bool[APP.GoodsNumber];
public bool[] GeneList
{
get
{
return this._GeneList;
}
}
public Chromosome()
{
for (int i = 0; i < APP.GoodsNumber; ++i)
{
this._GeneList[i] = ((APP.Rd.Next() % 2) == 0);
}
}
public Chromosome(Chromosome Father, Chromosome Mother)
{
int CutPoint = (APP.Rd.Next() % (APP.GoodsNumber - 1)) + 1;
Array.Copy(Father._GeneList, 0, this._GeneList, 0, CutPoint);
Array.Copy(Mother._GeneList, CutPoint, this._GeneList, CutPoint, APP.GoodsNumber - CutPoint);
if ((APP.Rd.Next() % APP.Mutation) == 0)
{
var MutationIndexList = APP.RandomSelect(APP.MutationNumber);
foreach (var Index in MutationIndexList)
{
this._GeneList[Index] = !this._GeneList[Index];
}
}
}
} public class Population
{
private Chromosome[] _ChromosomeList = new Chromosome[APP.PopulationSize];
public Chromosome[] ChromosomeList
{
get
{
return this._ChromosomeList;
}
} private Total Test(int Index, Chromosome pChromosome, Goods[] pGoodsList)
{
long WeightSum = 0;
long ValueSum = 0;
int i = 0;
foreach (var BValue in pChromosome.GeneList)
{
if (BValue)
{
WeightSum += pGoodsList[i].Weight;
ValueSum += pGoodsList[i].Value;
}
++i;
}
return new Total(Index, WeightSum, ValueSum);
} public Population()
{
for (int i = 0; i < APP.PopulationSize; ++i)
{
this._ChromosomeList[i] = new Chromosome();
}
} /// <summary>
/// 随机选取一个繁殖对象
/// </summary>
/// <returns></returns>
public int Select()
{
for (int i = 0; i < APP.PopulationSize; ++i)
{
if (APP.Rd.Next() % 2 == 0)
{
return i;
}
}
return APP.PopulationSize - 1;
}
/// <summary>
/// 随机选取两个不同的繁殖对象
/// </summary>
/// <param name="Index1"></param>
/// <param name="Index2"></param>
public void SelectDouble(out int Index1, out int Index2)
{
int I1 = -1, I2 = -1;
while (I1 == I2)
{
I1 = Select();
I2 = Select();
}
Index1 = I1;
Index2 = I2;
} /// <summary>
/// 总群演化方法
/// </summary>
/// <param name="pBag">背包</param>
/// <param name="pGoodsList">商品清单</param>
/// <returns></returns>
public Total[] Evolution(Bag pBag, Goods[] pGoodsList)
{
Total[] TotalList = new Total[this.ChromosomeList.Count()];
for (int i = 0; i < this.ChromosomeList.Count(); ++i)
{
TotalList[i] = Test(i, this.ChromosomeList[i], pGoodsList);
}
var OkList = TotalList.Where(p => p.TotalWeight <= pBag.Size).OrderByDescending(p => p.TotalValue);
var OutList = TotalList.Where(p => p.TotalWeight > pBag.Size).OrderByDescending(p =>
{
double BaseA = (double)p.TotalValue / p.TotalWeight;
double BaseB = ((double)pBag.Size * pBag.Size) / ((double)p.TotalWeight * p.TotalWeight);
return BaseA * BaseB;
}); var NewList = OkList.Concat(OutList).ToArray();
var SubChromosomeList = new Chromosome[APP.PopulationSize]; int FatherIndex;
int MotherIndex;
SelectDouble(out FatherIndex, out MotherIndex);
var Father = this.ChromosomeList[NewList[FatherIndex].Index];
var Mother = this.ChromosomeList[NewList[MotherIndex].Index]; for (int i = 0; i < SubChromosomeList.Count(); ++i)
{
if (i % 2 == 0)
{
SubChromosomeList[i] = new Chromosome(Father, Mother);
}
else
{
SubChromosomeList[i] = new Chromosome(Mother, Father);
SelectDouble(out FatherIndex, out MotherIndex);
Father = this.ChromosomeList[TotalList[FatherIndex].Index];
Mother = this.ChromosomeList[TotalList[MotherIndex].Index];
}
} this._ChromosomeList = SubChromosomeList; return NewList;
}
} public class APP
{
//伪随机数产生器
public static Random Rd = new Random();
//货物个数,对应染色体基因长度
public static int GoodsNumber = 200;
//突变比率倒数
public static int Mutation = 10;
//突变基因数量
public static int MutationNumber = 2;
//种群大小
public static int PopulationSize = 1000; /// <summary>
/// 从列表之中随机选取一定数量的元素
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="pList">源列表</param>
/// <param name="pLen">随机选取的元素列表长度</param>
/// <returns></returns>
public static List<T> GetRandomList<T>(IEnumerable<T> pList, int pLen)
{
if (pLen > pList.Count())
{
pLen = pList.Count();
}
List<T> TmpList = pList.ToList<T>();
List<T> DstList = new List<T>();
for (int i = 0; i < pLen && TmpList.Count() > 1; ++i)
{
int Index = APP.Rd.Next() % TmpList.Count();
DstList.Add(TmpList[Index]);
TmpList.RemoveAt(Index);
}
return DstList;
}
/// <summary>
/// 随机选取一定数量的Index序列
/// </summary>
/// <param name="Num">数量</param>
/// <returns></returns>
public static List<int> RandomSelect(int Num)
{
int[] NumList = new int[APP.GoodsNumber];
for (int i = 0; i < APP.GoodsNumber; ++i)
{
NumList[i] = i;
}
return GetRandomList<int>(NumList, Num);
} public APP()
{
#region 初始化背包与货物列表
Bag MyBag = new Bag(10000);
Goods[] GoodsList = new Goods[APP.GoodsNumber];
for (int i = 0; i < GoodsList.Count(); ++i)
{
GoodsList[i] = new Goods();
}
#endregion #region 创建总群与进行演化
Population iPopulation = new Population();
Total MaxTotal = null;
while (true)
{
var Fst = iPopulation.Evolution(MyBag, GoodsList).First();
if (MaxTotal == null)
{
MaxTotal = Fst;
}
else
{
if (Fst.TotalValue > MaxTotal.TotalValue)
{
MaxTotal = Fst;
}
}
//这里没有保存染色体,仅仅是取出当前总群的最优结果显示
Console.WriteLine("Value: " + MaxTotal.TotalValue + " Weight: " + MaxTotal.TotalWeight);
}
#endregion
}
} public class Program
{
static void Main(string[] args)
{
APP App = new APP();
}
}
}
CSharp遗传算法求解背包问题的更多相关文章
- 利用遗传算法求解TSP问题
转载地址 https://blog.csdn.net/greedystar/article/details/80343841 目录 一.问题描述 二.算法描述 三.求解说明 四.参考资料 五.源代码 ...
- 简单遗传算法求解n皇后问题
版权声明:本文为博主原创文章,转载请注明出处. 先解释下什么是8皇后问题:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行.同一列或同一斜线上,问有多少种摆法.在不 ...
- 基于遗传算法求解TSP问题(Java界面)
近期为做展示,改写了一个遗传算法求TSP的Java界面版,思路代码和 http://blog.csdn.net/wangqiuyun/article/details/12838903 这篇文章思路是一 ...
- 遗传算法求解TSP问题
package com.louis.tsp; /** * Project Name:GeneticAlgorithm * File Name:Individual.java * Package Nam ...
- 遗传算法求解旅行商(TSP)问题 -- python
参考资料: 遗传算法解决TSP旅行商问题(附:Python实现) 遗传算法详解(GA)(个人觉得很形象,很适合初学者) from itertools import permutations impor ...
- Python动态展示遗传算法求解TSP旅行商问题(转载)
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/jiang425776024/articl ...
- 经典递归问题:0,1背包问题 kmp 用遗传算法来解背包问题,hash表,位图法搜索,最长公共子序列
0,1背包问题:我写笔记风格就是想到哪里写哪里,有很多是旧的也没删除,代码内部可能有很多重复的东西,但是保证能运行出最后效果 '''学点高大上的遗传算法''' '''首先是Np问题的定义: npc:多 ...
- 遗传算法的C语言实现(二)-----以求解TSP问题为例
上一次我们使用遗传算法求解了一个较为复杂的多元非线性函数的极值问题,也基本了解了遗传算法的实现基本步骤.这一次,我再以经典的TSP问题为例,更加深入地说明遗传算法中选择.交叉.变异等核心步骤的实现.而 ...
- 遗传算法的简单应用-巡回旅行商(TSP)问题的求解
上篇我们用遗传算法求解了方程,其中用到的编码方式是二进制的编码,实现起来相对简单很多, 就连交配和变异等操作也是比较简单,但是对于TSP问题,就稍微复杂一点,需要有一定的策略, 才能较好的实现. 这次 ...
随机推荐
- python字符串之join
函数:string.join() Python中有join()和os.path.join()两个函数,具体作用如下: join():连接字符串数组.将字符串.元组.列表中的元素以指定的字符(分隔符)连 ...
- PAT Basic 1069. 微博转发抽奖(20)
小明PAT考了满分,高兴之余决定发起微博转发抽奖活动,从转发的网友中按顺序每隔N个人就发出一个红包.请你编写程序帮助他确定中奖名单. 输入格式: 输入第一行给出三个正整数M(<= 1000).N ...
- Debug.Assert vs Exception Throwing(转载)
来源 Q: I've read plenty of articles (and a couple of other similar questions that were posted on Stac ...
- Vuex详解笔记2
关于 state 每个vuex 应用只有一个 store 实例,所以使用起来不会太复杂,对于定位错误状态和操作会很方便. 简单用法:在vuex 的计算属性中返回vuex 的状态 最基本的使用方式,通过 ...
- 使用Github Pages和Hexo构建个人博客
Github Pages可以创建免费的静态站点,支持自带主题.支持自制页面等,并且可以使用Jekyll或者Hexo等静态博客框架进行管理. 独立博客是博客园等博客平台之外的一个良好补充,相比使用虚拟主 ...
- Spring MVC基础知识整理➣数据校验与格式化
概述 将view中Form的数据提交到后台之后,后台如何验证数据的有效性?在这里Spring MVC提供了相应的Hibernate类包(hibernate-validator-4.3.1.Final. ...
- 【BZOJ3782】上学路线
题解: 这个容斥以前做过 到i点的所有方案显然是个组合数 然后要减去不合法的方案数 我们可以考虑成减去到每个障碍点为第一次遇到的障碍然后之后乱走就可以了 因为模数不是质数,所以crt合并
- python 对象存储///对象序列化
如果你有写数据来之不易,并且希望每次都可以方便的读取,那么存储为一个对象是一个很不错的解决方法 方法一. import pickle #首先要导入包 dics={'a':4,'b':5,'c':6}# ...
- 关于input type=file上传图片的总结
最近比较忙,现在来整理一下近期的成果,方便以后再次使用. 关于图片上传的js 和jq jq $("input").change(function () { var $file = ...
- python---初始sqlite3
***sqllite不需要单独安装,python2.5以上自带的! ***官方中文文档:https://docs.python.org/2/library/sqlite3.html ***SQLite ...