-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.java
More file actions
82 lines (62 loc) · 2.22 KB
/
Population.java
File metadata and controls
82 lines (62 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
package aiproject1;
/**
*
* @author Layan
*/
public class Population {
Gene[] genes = new Gene[5000]; //array of genes
int optimal; //what we want to reach
public void initializePopulation(int size){
for (int i = 0; i < genes.length; i++) {
genes[i] = new Gene();
}
}
//get optimal gene
public Gene getOptimal(){
int lowerFit = Integer.MAX_VALUE; // the worst case
int maxOPTindex = 0;//
//loop to find lowest value fitness in array genes
for(int i=0;i<genes.length;i++){
if(lowerFit>=genes[i].fitness) //anything better than the worst case
lowerFit=genes[i].fitness;
maxOPTindex = i;
}
optimal = genes[maxOPTindex].fitness; // new optimal gene
return genes[maxOPTindex];// return the optimal gene
}//END GET OPTIMAL
//get gene with second lowest fitness for selection
public Gene getSecondOptimal(){
int lowfit1=0;
int lowfit2=0;
for(int i=0;i<genes.length;i++){
if(genes[i].fitness<genes[lowfit1].fitness){
lowfit2=lowfit1;
lowfit1=i;
}//end if
else if(genes[i].fitness<genes[lowfit2].fitness){
lowfit2=i;
}//end else
}//end for
//get gene with second lowest fitness for selection
return genes[lowfit2];
}//END GET SECOND OPTIMAL
//get least optimal gene index
public int getLeastOptimal(){
int LeastOptimalindex = 0;
int LeastOptimalValue=0;
for(int i=0;i<genes.length;i++){
if(LeastOptimalValue<=genes[i].fitness){
LeastOptimalValue=genes[i].fitness;
LeastOptimalindex=i;
}//end if
}//end for
return LeastOptimalindex;// return the least optimal gene index
}//END LEAST OPTIMAL INDEX
//calculate fitness for each gene
public void calculateFitnessAll(){
for (Gene gene : genes) {
gene.calcfitness();
} //end for
getOptimal();
}//END CALC FITNESS ALL
}//END POPULATION