我练习使用这个库,Jenetics.io。在他们的手册中,他们有一个例子,旅行推销员。该示例仅显示找到的最小路径,但不显示解决方案的点集或点顺序。如何获得解决方案的点集?
手册.. 第 129 页在此处输入链接描述
运行代码,结果:
[[D@79fc0f2f|[D@37a71e93|[D@4783da3f|[D@6e2c634b|[D@49097b5d|[D@378fd1ac|[D@5e9f23b4|[D@2dda6444|[D@50040f0c] -> 16.46284073991415
我使用的代码:
public class EncotrarRuta implements Problem<ISeq<double[]>,EnumGene<double[]>,Double>{
private final ISeq<double[]> _points;
private ArrayList<Double> puntosX = new ArrayList<>();
private ArrayList<Double> puntosY = new ArrayList<>();
public EncotrarRuta(ArrayList<Double> puntosX, ArrayList<Double> puntosY) {
this._points = null;
this.puntosX = puntosX;
this.puntosY = puntosY;
}
public EncotrarRuta(ISeq<double[]> points) {
this._points = requireNonNull(points);
}
@Override
public Function<ISeq<double[]>, Double> fitness() {
return p -> IntStream.range(0, p.length())
.mapToDouble(i -> {
final double[] p1 = p.get(i);
final double[] p2 = p.get((i+1)%p.size());
return hypot(p1[0]-p2[0],p1[1]-p2[1]);
}).sum();
}
@Override
public Codec<ISeq<double[]>, EnumGene<double[]>> codec() {
return Codecs.ofPermutation(_points);
}
public static EncotrarRuta of(ArrayList<Double> puntosX, ArrayList<Double> puntosY){
final MSeq<double[]> points = MSeq.ofLength(puntosX.size());
for (int i = 0; i < puntosX.size(); i++) {
points.set(i, new double[]{puntosX.get(i),puntosY.get(i)});
}
return new EncotrarRuta(points.asISeq());
}
public void run() {
EncotrarRuta encotrarRuta = EncotrarRuta.of(puntosX, puntosY);
Engine<EnumGene<double[]>,Double> engine = Engine
.builder(encotrarRuta)
.optimize(Optimize.MINIMUM)
.maximalPhenotypeAge(11)
.populationSize(500)
.alterers(
new SwapMutator<>(0.2),
new PartiallyMatchedCrossover<>(0.35))
.build();
EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
Phenotype<EnumGene<double[]>,Double> best = engine.stream()
.limit(bySteadyFitness(25))
.limit(250)
.peek(statistics)
.collect(toBestPhenotype());
System.out.println(best);
}
}