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
|
#include "Population.hpp"
Population::Population(unsigned popSize, unsigned eliteCount, unsigned chromosomeSize)
: m_popSize(popSize), m_eliteCount(eliteCount), m_chromosomeSize(chromosomeSize)
{
m_fitnesses.resize(m_popSize, 0.f);
m_chromosomes.resize(m_popSize);
for (auto &i : m_chromosomes)
{
i.resize(m_chromosomeSize, 0.f);
for (auto &j : i)
{
j = realRand(-1.f, 1.f);
}
}
}
void Population::roulleteWheel()
{
std::vector<Chromosome> newGeneration;
std::vector<unsigned> eliteIndexes(m_eliteCount, 0);
for (auto &i : eliteIndexes)
{
for (unsigned j = 0; j < m_popSize; ++j)
{
bool picked = false;
for (auto &k : eliteIndexes)
{
if (k == j)
{
picked = true;
break;
}
}
if (picked)
{
continue;
}
if (m_fitnesses[j] > m_fitnesses[i])
{
i = j;
}
}
}
for (auto &i : eliteIndexes)
{
newGeneration.push_back(m_chromosomes[i]);
}
unsigned fitnessSum = 0;
for (auto &i : m_fitnesses)
{
fitnessSum += i;
}
for (unsigned i = m_eliteCount; i < m_popSize; i += 2)
{
unsigned parentIndex = 0;
unsigned motherIndex = 0;
int randomParent = intRand(0, fitnessSum);
int randomMother = intRand(0, fitnessSum);
while (randomParent > 0)
{
randomParent -= m_fitnesses[parentIndex];
++parentIndex;
} --parentIndex;
while (randomMother > 0)
{
randomMother -= m_fitnesses[motherIndex];
++motherIndex;
} --motherIndex;
Chromosome child1;
Chromosome child2;
crossover(m_chromosomes[parentIndex], m_chromosomes[motherIndex], child1, child2);
mutate(child1);
mutate(child2);
newGeneration.push_back(child1);
newGeneration.push_back(child2);
}
if (newGeneration.size() < m_chromosomes.size())
{
newGeneration.push_back(newGeneration.back());
}
m_chromosomes = newGeneration;
m_fitnesses = std::vector<unsigned>(m_popSize, 0);
}
|