1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math.genetics;
18
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 import java.util.List;
22
23
24
25
26
27
28
29 public abstract class ListPopulation implements Population {
30
31
32 private List<Chromosome> chromosomes;
33
34
35 private int populationLimit;
36
37
38
39
40
41
42
43
44 public ListPopulation (List<Chromosome> chromosomes, int populationLimit) {
45 if (chromosomes.size() > populationLimit) {
46 throw new IllegalArgumentException("List of chromosomes bigger than maxPopulationSize.");
47 }
48 if (populationLimit < 0) {
49 throw new IllegalArgumentException("Population limit has to be >= 0");
50 }
51
52 this.chromosomes = chromosomes;
53 this.populationLimit = populationLimit;
54 }
55
56
57
58
59
60
61
62 public ListPopulation (int populationLimit) {
63 if (populationLimit < 0) {
64 throw new IllegalArgumentException("Population limit has to be >= 0");
65 }
66 this.populationLimit = populationLimit;
67 this.chromosomes = new ArrayList<Chromosome>(populationLimit);
68 }
69
70
71
72
73
74 public void setChromosomes(List<Chromosome> chromosomes) {
75 this.chromosomes = chromosomes;
76 }
77
78
79
80
81
82 public List<Chromosome> getChromosomes() {
83 return chromosomes;
84 }
85
86
87
88
89
90 public void addChromosome(Chromosome chromosome) {
91 this.chromosomes.add(chromosome);
92 }
93
94
95
96
97
98 public Chromosome getFittestChromosome() {
99
100 Chromosome bestChromosome = this.chromosomes.get(0);
101 for (Chromosome chromosome : this.chromosomes) {
102 if (chromosome.compareTo(bestChromosome) > 0) {
103
104 bestChromosome = chromosome;
105 }
106 }
107 return bestChromosome;
108 }
109
110
111
112
113
114 public int getPopulationLimit() {
115 return this.populationLimit;
116 }
117
118
119
120
121
122 public void setPopulationLimit(int populationLimit) {
123 this.populationLimit = populationLimit;
124 }
125
126
127
128
129
130 public int getPopulationSize() {
131 return this.chromosomes.size();
132 }
133
134
135
136
137 @Override
138 public String toString() {
139 return this.chromosomes.toString();
140 }
141
142
143
144
145
146
147 public Iterator<Chromosome> iterator() {
148 return chromosomes.iterator();
149 }
150 }