-
Notifications
You must be signed in to change notification settings - Fork 0
/
generation.cpp
101 lines (84 loc) · 2.22 KB
/
generation.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
#include <cassert>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include "generation.h"
Generation::Generation(vector<Individual*> &ind_points, int ind_num)
{
this->ind_points = ind_points;
this->ind_num = ind_num;
}
Generation::~Generation()
{
for (unsigned int i = 0; i < ind_points.size(); i++)
{
delete ind_points[i];
}
}
double Generation::get_max_fitness()
{
assert(ind_points.size() > 0);
double max, f;
max = ind_points[0]->get_fitness();
for (unsigned int i = 1; i < ind_points.size(); i++)
{
f = ind_points[i]->get_fitness();
if (f > max)
{
max = f;
}
}
return f;
}
double Generation::get_avg_fitness()
{
assert(ind_points.size() > 0);
double total = 0.0;
for (unsigned int i = 0; i < ind_points.size(); i++)
{
total += ind_points[i]->get_fitness();
}
return total / ind_points.size();
}
double Generation::get_variance_fitness()
{
assert(ind_points.size() > 1);
double sum_variance = 0;
double avg = get_avg_fitness();
for (unsigned int i = 0; i < ind_points.size(); i++)
{
sum_variance += pow(ind_points[i]->get_fitness() - avg, 2.0);
}
return sum_variance / (ind_points.size() - 1);
}
double Generation::get_std_fitness()
{
return pow(get_variance_fitness(), .5);
}
int Generation::produce(Generation* &p_next_gen)
{
unsigned int full_size = ind_num * 2;
vector<Individual*> p_new_inds;
Individual* p_ind = new Individual(*ind_points[0]);
p_new_inds.push_back(p_ind);
while (p_new_inds.size() < full_size)
{
Individual* p_dad = ind_points[rand() % ind_points.size()];
Individual* p_mom = ind_points[rand() % ind_points.size()];
Individual* p_son;
Individual* p_daughter;
p_dad->crossover(p_mom, p_son, p_daughter);
p_son->mutate();
p_daughter->mutate();
p_new_inds.push_back(p_son);
p_new_inds.push_back(p_daughter);
}
sort(p_new_inds.begin(), p_new_inds.end(), Generation::smaller);
while (p_new_inds.size() > ind_num)
{
p_new_inds.pop_back();
}
p_next_gen = new Generation(p_new_inds, ind_num);
return 1;
}