## Java遗传算法

### 基本原理

1. 初始化种群：随机生成一组初始解决方案，称为种群。
2. 适应度评估：计算每个个体的适应度，适应度越高，个体越优秀。
3. 选择操作：根据适应度选择一部分个体作为下一代的父代。
4. 交叉操作：通过交叉操作，将父代个体的基因组合起来生成子代个体。
5. 变异操作：对子代个体进行随机变异，引入新的基因组合。
6. 更新种群：用子代替换父代，形成新的种群。
7. 迭代优化：重复执行2-6步骤，直到满足终止条件。

### 基于Java的实现

``````import java.util.Random;

public class GeneticAlgorithm {

private static final int POPULATION_SIZE = 10;
private static final int GENE_LENGTH = 5;
private static final double MUTATION_RATE = 0.01;

private Random random;

public GeneticAlgorithm() {
random = new Random();
}

public int[] initialize() {
int[] population = new int[POPULATION_SIZE * GENE_LENGTH];
for (int i = 0; i < POPULATION_SIZE * GENE_LENGTH; i++) {
population[i] = random.nextInt(2);
}
return population;
}

public double calculateFitness(int[] individual) {
int sum = 0;
for (int i = 0; i < individual.length; i++) {
sum += individual[i];
}
return sum / (double) individual.length;
}

public int[] selection(int[] population) {
int[] selectedPopulation = new int[2 * GENE_LENGTH];
for (int i = 0; i < 2 * GENE_LENGTH; i++) {
selectedPopulation[i] = population[random.nextInt(POPULATION_SIZE * GENE_LENGTH)];
}
return selectedPopulation;
}

public int[] crossover(int[] parent1, int[] parent2) {
int[] child = new int[GENE_LENGTH];
int crossoverPoint = random.nextInt(GENE_LENGTH);
for (int i = 0; i < GENE_LENGTH; i++) {
if (i < crossoverPoint) {
child[i] = parent1[i];
} else {
child[i] = parent2[i];
}
}
return child;
}

public void mutation(int[] child) {
for (int i = 0; i < GENE_LENGTH; i++) {
if (random.nextDouble() < MUTATION_RATE) {
child[i] = 1 - child[i];
}
}
}

public void evolve(int[] population) {
int[] newPopulation = new int[POPULATION_SIZE * GENE_LENGTH];
for (int i = 0; i < POPULATION_SIZE; i++) {
int[] parent1 = selection(population);
int[] parent2 = selection(population);
int[] child = crossover(parent1, parent2);
mutation(child);
System.arraycopy(child, 0, newPopulation, i * GENE_LENGTH, GENE_LENGTH);
}
System.arraycopy(newPopulation, 0, population, 0, POPULATION_SIZE * GENE_LENGTH);
}

public static void main(String[] args) {
GeneticAlgorithm ga = new GeneticAlgorithm();
int[] population = ga.initialize();
for (int i = 0; i < 100; i++) {
ga.evolve(population);
}
double fitness = ga.calculateFitness(population);
System.out.println("Best fitness: " + fitness);
}
}
``````

### 序列图

``````sequenceDiagram
participant User
participant Algorithm
participant Population

User->>``````