public class Population { private Individual population[]; private double populationFitness = -1; public Population(int populationSize) { this.population = new Individual[populationSize]; } public Population(int populationSize, Bootstrap bootstrap) { this.population = new Individual[populationSize]; for (int individualCount = 0;individualCount<populationSize;individualCount++){ Individual individual = new Individual(bootstrap); population[individualCount] = individual; } } public Individual[] getPopulation() { return this.population; } public Individual getFittest(int offset) { Arrays.sort(this.population, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { if (o1.getFitness() > o2.getFitness()) { return -1; } else if (o1.getFitness() < o2.getFitness()) { return 1; } return 0; } }); return this.population[offset]; } public void setPopulationFitness(double fitness) { this.populationFitness = fitness; } public double getPopulationFitness() { return this.populationFitness; } public int size() { return this.population.length; } public Individual setIndividual(int offset, Individual individual) { return population[offset] = individual; } public Individual getIndividual(int offset) { return population[offset]; } public void shuffle() { Random r = new Random(); for (int i = population.length -1; i > 0; i--) { int index = r.nextInt(i+1); Individual individual = population[index]; population[index] = population[i]; population[i] = individual; } } }
时间: 2023-07-14 15:12:07 浏览: 74
Ruby 之 class 中的 private、 protected、public
这段代码是一个遗传算法中的种群类,用于存储和操作个体(Individual)的集合。其中包括:
- 两个构造函数:一个是创建一个指定大小的空种群,另一个是根据给定的 Bootstrap 对象创建一个指定大小的种群,每个个体都是由该 Bootstrap 对象随机生成的;
- getPopulation() 方法:返回整个种群的个体数组;
- getFittest(int offset) 方法:返回种群中第 offset 个最适应的个体。这里使用了一个 Comparator 对象,按照个体的适应度进行排序,然后返回指定位置的个体;
- setPopulationFitness(double fitness) 和 getPopulationFitness() 方法:用于设置和获取整个种群的适应度;
- size() 方法:返回种群的大小;
- setIndividual(int offset, Individual individual) 和 getIndividual(int offset) 方法:用于设置和获取指定位置的个体;
- shuffle() 方法:将种群中的个体随机交换位置,以打乱顺序。
通过这些方法,种群可以被用于进化算法的迭代过程中,从而不断优化个体的适应度。
阅读全文