📄 ackminimizing.java
字号:
import java.io.*;
import org.jgap.*;
import org.jgap.data.*;
import org.jgap.impl.*;
import org.jgap.xml.*;
import org.w3c.dom.*;
public class ACKMinimizing {
private final static String CVS_REVISION = "$Revision: 1.23 $";
/**
* The total number of times we'll let the population evolve.
*/
private static final int MAX_ALLOWED_EVOLUTIONS = 200;
public static void makeChangeForAmount()
throws Exception {
// Start with a DefaultConfiguration, which comes setup with the
// most common settings.
// -------------------------------------------------------------
Configuration conf = new DefaultConfiguration();
conf.setPreservFittestIndividual(true);
FitnessFunction myFunc =new ACKMinimizingFitnessFunction();
conf.setFitnessFunction(myFunc);
Gene[] myGenes = new Gene[30];
for(int i=0;i<30;i++){
myGenes[i]=new DoubleGene(conf, -5.0, 5.0);
}
IChromosome myChromosome = new Chromosome(conf, myGenes);
conf.setSampleChromosome(myChromosome);
conf.setPopulationSize(1000);
Genotype population;
// Now we initialize the population randomly, anyway (as an example only)!
// If you want to load previous results from file, remove the next line!
// -----------------------------------------------------------------------
population = Genotype.randomInitialGenotype(conf);
// Evolve the population. Since we don't know what the best answer
// is going to be, we just evolve the max number of times.
// ---------------------------------------------------------------
long startTime = System.currentTimeMillis();
for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) {
if (!uniqueChromosomes(population.getPopulation())) {
throw new RuntimeException("Invalid state in generation "+i);
}
population.evolve();
}
long endTime = System.currentTimeMillis();
System.out.println("Total evolution time: " + ( endTime - startTime)
+ " ms");
IChromosome bestSolutionSoFar = population.getFittestChromosome();
System.out.println("The best solution has a fitness value of " +
bestSolutionSoFar.getFitnessValue());
System.out.println("It contained the following: ");
for(int i=0;i<30;i++){
System.out.println("\t" +
ACKMinimizingFitnessFunction.
getValueAtGene(
bestSolutionSoFar, i));
}
}
public static void main(String[] args)
throws Exception {
makeChangeForAmount();
}
public static boolean uniqueChromosomes(Population a_pop) {
for(int i=0;i<a_pop.size()-1;i++) {
IChromosome c = a_pop.getChromosome(i);
for(int j=i+1;j<a_pop.size();j++) {
IChromosome c2 =a_pop.getChromosome(j);
if (c == c2) {
return false;
}
}
}
return true;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -