Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class Population {
- Point[] points;
- int population_size;
- int max = 10;
- int min = -10;
- int tournament_size = 5;
- int point_count = 0;
- public Population(int population_size) {
- points = new Point[population_size];
- for (int i = 0; i < population_size; i++) {
- points[i] = new Point();
- }
- this.population_size = population_size;
- randomizePopulation();
- }
- public void randomizePopulation() {
- for (int i = 0; i < population_size; i++) {
- points[i].x = min + Math.random() * (max - min);
- points[i].y = min + Math.random() * (max - min);
- }
- }
- public Population evolution() {
- //print(this,this.population_size);
- double[] results = new double[this.population_size];
- for (int i = 0; i < population_size; i++) {
- results[i] = GeneticAlgorithm.function.calculate(points[i].x, points[i].y);
- }
- Point best = getFittest();
- System.out.println("Najlepsza wartosc " + calculate_fittness(best));
- Population newpopulation = new Population(this.population_size);
- for (int j = 0; j < this.population_size; j++) {
- Point parent1 = tournament(this);
- Point parent2 = tournament(this);
- crossover(parent1, parent2, newpopulation);
- if (this.population_size == this.point_count) break;
- }
- this.point_count = 0;
- return newpopulation;
- }
- public void crossover(Point parent1 , Point parent2,Population newpopulation)
- {
- newpopulation.points[point_count].x=parent1.x;
- newpopulation.points[point_count].y=parent2.x;
- point_count+=1;
- newpopulation.points[point_count].x=parent1.y;
- newpopulation.points[point_count].y=parent2.y;
- point_count+=1;
- }
- public Point tournament(Population population)
- {
- Population tournament = new Population(this.tournament_size);
- for(int i = 0 ; i< this.tournament_size ; i++)
- {
- int index = (int) (Math.random() * this.population_size);
- tournament.points[i] = population.points[index];
- }
- Point parent = tournament.getFittest();
- return parent;
- }
- public Point getFittest()
- {
- double fittest = calculate_fittness(points[0]);
- Point x = this.points[0];
- for(int i=1;i<population_size;i++)
- {
- if(fittest> calculate_fittness(points[i]))
- {
- fittest=calculate_fittness(points[i]);
- x=this.points[i];
- }
- }
- return x;
- }
- public double calculate_fittness(Point p)
- {
- return GeneticAlgorithm.function.calculate(p.x,p.y);
- }
- public void print(Population population, int size)
- {
- for(int i=0;i<size;i++)
- {
- //System.out.println(population.points[i].x +" "+population.points[i].y);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement