-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndividual.cpp
More file actions
128 lines (93 loc) · 2.3 KB
/
Individual.cpp
File metadata and controls
128 lines (93 loc) · 2.3 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
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
#include "Individual.h"
#include <sstream>
#include <iostream>
using namespace NGroupingChallenge;
using namespace std;
Individual::Individual(int genotypeLen): gen(rd()), fitness(0.0), genotypeLen(genotypeLen) {}
Individual::Individual(int genotypeLen, int maxValue)
: gen(rd()), fitness(0.0), genotypeLen(genotypeLen)
{
uniform_int_distribution<> dist(1, maxValue);
for (int i = 0; i < genotypeLen ; i++)
{
genotype.push_back(dist(gen));
}
}
Individual::Individual(Individual& other) : gen(rd())
{
this->genotype = other.genotype;
this->fitness = other.fitness;
this->genotypeLen = other.genotypeLen;
}
double Individual::evaluateFitness(CGroupingEvaluator& evaluator)
{
fitness = evaluator.dEvaluate(genotype);
return fitness;
}
void Individual::mutate(double mutProb, int maxValue)
{
uniform_real_distribution<> distD(0, 1);
uniform_int_distribution<> distI(1, maxValue);
for (int i = 0; i < genotypeLen; i++)
{
if (distD(gen) < mutProb) {
genotype[i] = distI(gen);
}
}
}
vector<Individual*> Individual::cross(Individual& other, int numOfChildren)
{
uniform_int_distribution<> dist(1, genotypeLen-1);
int cutPoint = dist(gen);
vector<Individual*> children;
// ---BEFORE MODIFICATION---
/*for (size_t i = 0; i < cutPoint; i++)
{
firstChild->genotype.push_back(genotype[i]);
secondChild->genotype.push_back(other.genotype[i]);
}
for (size_t i = cutPoint; i < genotypeLen; i++)
{
firstChild->genotype.push_back(other.genotype[i]);
secondChild->genotype.push_back(genotype[i]);
}*/
for (int i = 0; i < numOfChildren; i++)
{
children.push_back(this->makeChild(other));
}
return children;
}
string Individual::genotypeString()
{
ostringstream oss;
oss << "[";
for (size_t i = 0; i < genotypeLen; ++i) {
oss << genotype[i];
if (i != genotypeLen - 1) {
oss << ",";
}
}
oss << "]";
string result = oss.str();
return result;
}
double Individual::getFitness()
{
return fitness;
}
Individual* Individual::makeChild(Individual& other)
{
Individual* child = new Individual(genotypeLen);
uniform_int_distribution<> dist(1, 2);
for ( int i = 0; i < genotypeLen; i++)
{
int random = dist(gen);
if (random == 1) {
child->genotype.push_back(genotype[i]);
}
else {
child->genotype.push_back(other.genotype[i]);
}
}
return child;
}