java代码实现遗传算法
时间: 2023-11-10 22:07:13 浏览: 90
好的,以下是一个简单的Java代码实现遗传算法的示例:
```java
import java.util.Random;
public class GeneticAlgorithm {
private int populationSize;
private double mutationRate;
private double crossoverRate;
private int elitismCount;
public GeneticAlgorithm(int populationSize, double mutationRate, double crossoverRate, int elitismCount) {
this.populationSize = populationSize;
this.mutationRate = mutationRate;
this.crossoverRate = crossoverRate;
this.elitismCount = elitismCount;
}
public Population evolvePopulation(Population population) {
Population newPopulation = new Population(population.size());
// Keep the best individuals from the current population
for (int i = 0; i < elitismCount; i++) {
newPopulation.saveIndividual(i, population.getFittest(i));
}
// Crossover
for (int i = elitismCount; i < population.size(); i++) {
Individual parent1 = selectParent(population);
Individual parent2 = selectParent(population);
Individual child = crossover(parent1, parent2);
newPopulation.saveIndividual(i, child);
}
// Mutation
for (int i = elitismCount; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
}
private Individual selectParent(Population population) {
Random random = new Random();
int tournamentSize = 5;
Population tournament = new Population(tournamentSize);
for (int i = 0; i < tournamentSize; i++) {
int randomIndex = random.nextInt(population.size());
tournament.saveIndividual(i, population.getIndividual(randomIndex));
}
return tournament.getFittest(0);
}
private Individual crossover(Individual parent1, Individual parent2) {
Individual child = new Individual(parent1.getChromosomeLength());
Random random = new Random();
for (int i = 0; i < parent1.getChromosomeLength(); i++) {
if (random.nextDouble() <= crossoverRate) {
child.setGene(i, parent1.getGene(i));
} else {
child.setGene(i, parent2.getGene(i));
}
}
return child;
}
private void mutate(Individual individual) {
Random random = new Random();
for (int i = 0; i < individual.getChromosomeLength(); i++) {
if (random.nextDouble() <= mutationRate) {
int gene = random.nextInt(2);
individual.setGene(i, gene);
}
}
}
}
```
这个示例中,我们定义了一个遗传算法类 `GeneticAlgorithm`,它包含了一些参数,如种群大小、变异率、交叉率和精英数量。我们还定义了一些方法,如 `evolvePopulation`、`selectParent`、`crossover` 和 `mutate`,用于执行遗传算法的不同步骤。
阅读全文