用Java写个遗传算法基础模型
时间: 2023-03-23 09:01:35 浏览: 86
好的,以下是一个用Java编写的遗传算法基础模型:
```java
import java.util.Random;
public class GeneticAlgorithm {
// 种群数量
private int populationSize;
// 基因序列长度
private int geneLength;
// 目标基因序列
private int[] targetGene;
// 种群
private int[][] population;
// 种群中每个个体的适应度
private int[] fitness;
// 随机数生成器
private Random random;
public GeneticAlgorithm(int populationSize, int geneLength, int[] targetGene) {
this.populationSize = populationSize;
this.geneLength = geneLength;
this.targetGene = targetGene;
this.population = new int[populationSize][geneLength];
this.fitness = new int[populationSize];
this.random = new Random();
initializePopulation();
}
// 初始化种群
private void initializePopulation() {
for (int i = 0; i < populationSize; i++) {
for (int j = 0; j < geneLength; j++) {
population[i][j] = random.nextInt(2);
}
}
}
// 计算种群中每个个体的适应度
private void calculateFitness() {
for (int i = 0; i < populationSize; i++) {
int score = 0;
for (int j = 0; j < geneLength; j++) {
if (population[i][j] == targetGene[j]) {
score++;
}
}
fitness[i] = score;
}
}
// 选择个体进行交叉
private int[] selectParent() {
int[][] selectedParents = new int[2][geneLength];
for (int i = 0; i < 2; i++) {
int index1 = random.nextInt(populationSize);
int index2 = random.nextInt(populationSize);
selectedParents[i] = fitness[index1] > fitness[index2] ? population[index1] : population[index2];
}
return selectedParents[0];
}
// 交叉
private int[] crossover(int[] parent1, int[] parent2) {
int crossoverPoint = random.nextInt(geneLength);
int[] child = new int[geneLength];
for (int i = 0; i < geneLength; i++) {
if (i < crossoverPoint) {
child[i] = parent1[i];
} else {
child[i] = parent2[i];
}
}
return child;
}
// 变异
private void mutate(int[] child) {
for (int i = 0; i < geneLength; i++) {
if (random.nextDouble() < 0.01) {
child[i] = child[i] == 0 ? 1 : 0;
}
}
}
// 进化
public int[] evolve() {
calculateFitness();
int[] parent1 = selectParent();
int[] parent2 = selectParent();
int[] child = crossover(parent1, parent2);
mutate(child);
return child;
}
}
```
这是一个简单的遗传算法实现,可以使用它来求解基因序列匹配问题。您可以根据自
阅读全文