【Title】[原]遗传算法Java实现源代码
【Date】2013-04-07
【Abstract】以前学习遗传算法时,用Java实现的遗传算法程序,现整理分享出来。
【Keywords】wintys、遗传、算法、algorithm、种群、基因、个体、进化、染色体、适应度、Rosenbrock
【Environment】Windows 7、PowerDesigner16
【Author】wintys (wintys@gmail.com) http://wintys.cnblogs.com
【URL】http://www.cnblogs.com/wintys/archive/2013/04/07/genetic_algorithms.html
【Content】:
1、简介
此程序是对照《遗传算法原理及应用》(周明、孙树栋编著),附录所列C程序改编而来,用Java实现的遗传算法程序。相关理论请参考《遗传算法原理及应用》。
2、类图
类图由源代码经PowerDesigner反向生成。
(类图)
3、代码
3.1、染色体
//染色体:Chromesone.java
class Chromosome implements Cloneable{
private StringBuffer chromosome;
private int chromosomeLength;//染色体长度
private char defaultChar; //默认基因填充字符
public Chromosome(int chromosomeLength){
chromosome = new StringBuffer(chromosomeLength);
chromosome.setLength(chromosomeLength);
defaultChar = '0';
this.chromosomeLength = chromosomeLength;
}
//设置基因
public boolean setGene(int begin , int end , String gene){
int len = gene.length();
if(len > end - begin + 1)
return false;
//index => chromosome , idx => gene
for (int index = begin , idx = 0; index <= end; index++ , idx++) {
if(idx < len)
chromosome.setCharAt(index , gene.charAt(idx));
else
chromosome.setCharAt(index , defaultChar);
}
return true;
}
//获取基因
public String getGene(int begin , int end){
char[] dest = new char[end - begin + 1];
chromosome.getChars(begin , end + 1 , dest , 0);
return new String(dest);
}
public int getLength(){
return chromosomeLength;
}
public String toString(){
return chromosome.toString();
}
@Override
public Object clone()throws CloneNotSupportedException{
Chromosome c = null;
try{
c = (Chromosome)super.clone();
c.chromosome = new StringBuffer(chromosome);
}catch(CloneNotSupportedException e ){
System.out.println(e.getMessage());
}
return c;
}
}
3.2、个体
3.2.1、抽象个体
//Individual.java
abstract class Individual implements Cloneable{
protected Chromosome chrom;//个体基因型:一个基因型染色体由多个基因组成
protected int genelen;//基因长度
protected double fitness;//适应度
protected double targetValue;//目标函数值
public abstract void coding();//编码
public abstract void decode();//解码
public abstract void calFitness();//计算个体适应度
public abstract void generateIndividual();//随机产生个体
public abstract void calTargetValue();//获取目标函数值
public double getFitness(){
return fitness;
}
public double getTargetValue(){