-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneticalgorithm.cpp
More file actions
59 lines (49 loc) · 1.14 KB
/
geneticalgorithm.cpp
File metadata and controls
59 lines (49 loc) · 1.14 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
#include "geneticalgorithm.h"
void GeneticAlgorithm::createGenePool(std::vector<Rocket> &rockets)
{
genePool.clear();
double maxfit = 0;
for (int i = 0; i < (int)rockets.size(); i++)
{
if (rockets[i].getFitness() > maxfit)
{
maxfit = rockets[i].getFitness();
}
}
for (int i = 0; i < (int)rockets.size(); i++)
{
rockets[i].setFitness(rockets[i].getFitness() / maxfit);
}
for (int i = 0; i < (int)rockets.size(); i++)
{
int n = (int)(rockets[i].getFitness() * 100);
for (int j = 0; j < n; j++)
{
genePool.push_back(rockets[i].getDna());
}
}
}
std::vector<sf::Vector2f> GeneticAlgorithm::evolve(float mutationRate)
{
std::vector<sf::Vector2f> parentA, parentB, child;
parentA = genePool[rand() % genePool.size()];
parentB = genePool[rand() % genePool.size()];
sf::Vector2f gene;
for (int i = 0; i < (int)parentA.size(); i++)
{
if ((float)(rand() % 101) < (mutationRate / genePool.size()))
{
gene = sf::Vector2f((float)(rand() % 3 - 1), (float)(rand() % 3 - 1));
}
else if (i < rand() % genePool.size())
{
gene = parentA[i];
}
else
{
gene = parentB[i];
}
child.push_back(gene);
}
return child;
}