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问题,就稍微复杂一点,需要有一定的策略, 才能较好的实现. 这次 ...
随机推荐
- maven如果正常配置不成功,就按照我的就可以配置成功了
常规的配置如下 非常规的配置 如果上面都没有问题,还是不能创建成功,就是maven配路径的问题,如图所示 如下图所示即是正确配置
- 华硕X75VB安装ubuntu12.10网卡不可用等相关问题总结
笔记本相关信息: 电脑型号:华硕X75VB 笔记本电脑 处理器:i5-3230M 2.60GHz 双核 主板:华硕X75VB (英特尔 Ivy Bridge - HM76 Express芯片组) 内存 ...
- Supervisor Linux程序进程管理
Supervisor 介绍 在linux或者unix操作系统中,守护进程(Daemon)是一种运行在后台的特殊进程,它独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事件.由于在linux中 ...
- python--使用递归的方式建立二叉树
树和图的数据结构,就很有意思啦. # coding = utf-8 class BinaryTree: def __init__(self, root_obj): self.key = root_ob ...
- python爬虫实例
import re import requests from bs4 import BeautifulSoup # 主方法 def main(): # 给请求指定一个请求头来模拟chrome浏览器 h ...
- Visual Studio "14" CTPs
下载地址:http://www.visualstudio.com/en-us/downloads/visual-studio-14-ctp-vs 上张有亮点的图: 实现亮点的方法(Remo ...
- springboot中使用拦截器、监听器、过滤器
拦截器.过滤器.监听器在web项目中很常见,这里对springboot中怎么去使用做一个总结. 1. 拦截器(Interceptor) 我们需要对一个类实现HandlerInterceptor接 ...
- flink--DateSet开发--简单入门
开发流程 1. 获得一个execution environment, 2. 加载/创建初始数据, 3. 指定这些数据的转换, 4. 指定将计算结果放在哪里, 5. 触发程序执行 例子: object ...
- day60 pymysql
预知扩展内容,详见地址如下(关于数据库备份和恢复) http://www.cnblogs.com/linhaifeng/articles/7525619.html 我们一般写程序都是在py文件里面,那 ...
- java分页实现
虽然现在有很多好用的框架,对分页进行支持,很简单的就把分页的效果做出来,但是如果自己手写是一个怎样的流程的?今天就来说说它,手动实现分页效果. 一.分页的思路 首先我们得知道写分页代码时的思路,保持思 ...