-
Notifications
You must be signed in to change notification settings - Fork 0
/
Population.cpp
141 lines (115 loc) · 2.58 KB
/
Population.cpp
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "Population.h"
void Population::addToPopulation(Chromosome ch){
List.push_back(ch);
}
std::list<Chromosome> Population::getPopulation(){
return List;
}
void Population::setCrossoverPoint(int a){
crossoverPoint=a;
}
int Population::getCrossoverPoint(){
return crossoverPoint;
}
std::list<Chromosome> Population::getFittestChromosomes(){
int a[List.size()];
int b=0;
if(List.size()>1){
std::list<Chromosome>::iterator it;
for(it=List.begin();it!=List.end();it++){
Chromosome ch=*it;
a[b]=ch.getFitnessScore();
b++;
}
int n = sizeof(a)/sizeof(a[0]);
std::sort(a, a+n);
std::list<Chromosome> arr;
for(it=List.begin();it!=List.end();it++){
Chromosome ch=*it;
if(ch.getFitnessScore()==a[0] || ch.getFitnessScore()==a[1])
arr.push_back(ch);
}
return arr;
}
else{
std::cout<<"Not enough chromosomes in the population for crossover\n";
return {};
}
}
std::map<Slot*,int> Population::performCrossover(std::list<Chromosome> q){
Chromosome a=q.front();
Chromosome b=q.back();
Slot *s;
int count=0;
int c=getCrossoverPoint();
std::map<Slot*,int> map1=a.getHashMap();
std::map<Slot*,int> map2=b.getHashMap();
std::map<Slot*,int> map3;
std::map<Slot*,int>::iterator it;
std::map<Slot*,int>::iterator it2;
for(it=map1.begin();it!=map1.end();it++){
if(count==c){
s=it->first;
break;
}
count++;
}
it2=map1.find(s);
for(it=map1.begin();it->first!=it2->first;it++){
map3[it->first]=it->second;
}
count=0;
for(it=map2.begin();it!=map2.end();it++){
if(count==c){
s=it->first;
break;
}
count++;
}
for(it=map2.find(s);it!=map2.end();it++){
map3[it->first]=it->second;
}
return map3;
}
std::map<Slot*,int> Population::mutation(std::map<Slot*,int> a){
int position=0;
std::map<Slot*,int>::iterator it;
std::map<Slot*,int> Map;
for(it=a.begin();it!=a.end();it++){
if(Map.size()<a.size()){
Map[it->first]=position;
position++;
}
}
return Map;
}
void Population::addOffspring(std::map<Slot*,int> map){
Chromosome ch;
std::map<Slot*,int>::iterator it;
std::list<Slot*> l;
int size=0;
for(it=map.begin();it!=map.end();it++){
if(it->second==size)
l.push_back(it->first);
else{
ch.addList(l);
l.clear();
size++;
it--;
}
}
if(!(l.empty()))
ch.addList(l);
std::list<Chromosome>::iterator it2;
for(it2=List.begin();it2!=List.end();it2++){
if(ch.getFitnessScore()>(*it2).getFitnessScore()){
List.push_back(ch);
break;
}
else
std::cout<<"Chromosome not fitter\n";
}
for(it2=List.begin();it2!=List.end();it2++){
std::cout<<(*it2).getFitnessScore()<<"\n";
}
}