gaacrossover.java

来自「Java实现的遗传算法工具集:GA Playground」· Java 代码 · 共 60 行

JAVA
60
字号

public class GaaCrossover {
	
	int gaType;
	int crossoverType;
	double crossoverRate;
	
	public GaaCrossover (GaaProblem problem) {
		
		gaType = problem.gaType;
		crossoverType = problem.crossoverType;
		crossoverRate = problem.crossoverRate;
		
	}


	public String crossover(String chrom1, String chrom2) {
		
		int i, pos;
		String s1, s2, s;
		char kar;

		s = "";
		
		switch (gaType) {
			case 1:
				if (GaaMisc.flip(crossoverRate)) {
					pos =(int) Math.floor((Math.random()*chrom1.length()));
					s1 = chrom1.substring(0,pos);
					s2 = chrom2.substring(pos);
					s = s1.concat(s2);
				}
				else
					s = chrom1;
				break;
			case 2:
				if (GaaMisc.flip(crossoverRate)) {
					pos =(int) Math.floor((Math.random()*chrom1.length()));
					s = chrom1.substring(0,pos);
					StringBuffer sb = new StringBuffer(s);
					for (i=0;i<chrom2.length();i++) {
						kar = chrom2.charAt(i);
						if (s.indexOf(kar) == -1) {
							sb.append(kar);
						}
						s = sb.toString();
					}
				}
				else
					s = chrom1;
				break;
		}

		return s;

	}		
	
	
	
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?