安卓-Java交叉算法
我正在为TSP问题开发安卓应用程序
我有一个交叉算法,我想尽量减少循环数,以更快的算法。 我怎么能做到
代码如下:
public static Path crossover(Path dad, Path mom) {
//Create new child path
Path child = new Path();
//Get start and sub path positions for dads path
double startPos = (double) (Math.random() * dad.pathSize());
double endPos = (double) (Math.random() * dad.pathSize());
//Loop and add the sub path from dad to our child
for (int i = 0; i < child.pathSize(); i++) {
//If our start position is less than the end position
if (startPos < endPos && i > startPos && i < endPos) {
child.setDestination(i, dad.getDestination(i));
} // if our start position is larger
else if (startPos > endPos) {
if (!(i < startPos && i > endPos)) {
child.setDestination(i, dad.getDestination(i));
}
}
}
// Loop through mom destination path
for (int i = 0; i < mom.pathSize(); i++){
// If child doesn't have the destination add it
if (!child.containsDestination(mom.getDestination(i))) {
// Loop to find a spare position in the child's path
for (int j = 0; j < child.pathSize(); j++) {
//Spare position found, add destination
if (child.getDestination(j) == null) {
child.setDestination(j, mom.getDestination(i));
break;
}
}
}
}
return child;
}
# 1 楼答案
如果我正确理解GA交叉,您可以只使用一个for loop从家长处返回一个孩子
请查看我的示例代码: