forked from cppnuts-yt/Optimization-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Population.cpp
86 lines (79 loc) · 2.26 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
#include <iostream>
#include <vector>
#include "dna.cpp"
using namespace std;
class Population{
private:
vector<Dna> population;
vector<Dna> matingPool;
int generation;
bool finished;
Dna target;
float mutationRate;
float perfectScore = 1;
public:
Population(Dna target):target{target},finished{false}{
}
void setMutationRate(float mr){mutationRate=mr;}
void initializePopulation(int popMax){
int len = target.gens.length();
for(int j=0; j<popMax; j++){
population.push_back(Dna(len));
}
cout << "population initialized with " << population.size() << endl;
}
void printPopulation() const{
for(auto elem: population){
cout << elem.gens << endl;
}
}
void calFitness(){
for(auto& elem: population){
elem.calFitness(target);
if(elem.fitness == target.fitness){
cout << "found it";
cout << elem.gens << endl;
finished = true;
break;
}
}
}
float getMaxScore(){
float maxScore =0.0;
for(auto& elem: population){
//cout << "elem.fitness " << elem.fitness << endl;
if(maxScore < elem.fitness)
maxScore = elem.fitness;
}
cout << maxScore << endl;
return maxScore;
}
void buildMatPool(){
float max = getMaxScore();
if(max<=0){
cout << "max calculation is zero";
max = 1;
}
cout << "maxScore " << max << endl;
for(auto & elem: population){
float n = floor(elem.fitness/max);
for(int i=0; i<n*100; i++){
matingPool.push_back(elem);
}
}
}
void generate(){
for(int i=0; i<population.size(); i++){
int a = floor(rand()%matingPool.size());
int b = floor(rand()%matingPool.size());
Dna partnerA = matingPool[a];
Dna partnerB = matingPool[b];
Dna child = partnerA.crossover(partnerB);
child.mutate(this->mutationRate);
population[i] = child;
}
}
bool isFinished(){
return finished;
}
};