-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.java
More file actions
94 lines (78 loc) · 2.22 KB
/
Population.java
File metadata and controls
94 lines (78 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Population
{
public ArrayList<Chromosome> chromosomes = new ArrayList<>();
public Population() { this.chromosomes=new ArrayList<>(); }
public Population(ArrayList<Chromosome> chromosomes)
{
for(int i=0; i<chromosomes.size(); i++)
{
Chromosome c = new Chromosome (chromosomes.get(i));
this.add(c);
}
}
public void add(Chromosome c) {
chromosomes.add(c);
}
public int size() {
return this.chromosomes.size();
}
public int indexOf(Chromosome c) {
return this.chromosomes.indexOf(c);
}
public void remove(int index) {
this.chromosomes.remove(index);
}
public Chromosome get(int i) {
return chromosomes.get(i);
}
public Population addTwoPopulation(Population p1, Population p2)
{
Population ret = new Population();
for (int i = 0; i < p1.size(); i++)
{
Chromosome c=new Chromosome(p1.get(i));
ret.add(c);
}
for (int i = 0; i < p2.size(); i++)
{
Chromosome c=new Chromosome(p2.get(i));
ret.add(c);
}
return ret;
}
public Population sortByFitness(Population p1)
{
ArrayList<Chromosome> ret = new ArrayList<>();
for(int i=0; i<p1.chromosomes.size(); i++)
{
Chromosome c=new Chromosome(p1.get(i));
ret.add(c);
}
Collections.sort(ret, new Comparator<Chromosome>()
{
@Override
public int compare(Chromosome p1, Chromosome p2) {
float p1f=p1.fitness;
float p2f=p2.fitness;
if(p1f>p2f)
{
return 1;
}
else if(p1f<p2f)
{
return -1;
}
else
{
return 0; // Ascending
}
}
});
ret.sort(Comparator.comparingDouble(Chromosome::getFitness)); //smallest to largest
Collections.reverse(ret);
return new Population(ret);
}
}