-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.cpp
More file actions
83 lines (62 loc) · 2.51 KB
/
Copy pathPopulation.cpp
File metadata and controls
83 lines (62 loc) · 2.51 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
#include "Population.h"
void Population::generate_individuals(int no_individuals, const Graph &graph) {
for (int i = 0; i < no_individuals; i++) {
Individual individual(graph, evaluator_);
population_vector_.push_back(individual);
}
}
Population::Population(int no_individuals, const Graph &graph, double mutation_probability,
const Evaluator &evaluator) {
graph_ = graph;
mutation_probability_ = mutation_probability;
evaluator_ = evaluator;
generate_individuals(no_individuals, graph);
}
std::ostream &operator<<(std::ostream &os, const Population &population) {
for (const Individual &individual : population.population_vector_) {
os << individual << "\n";
}
return os;
}
const Individual &Population::operator[](int index) const {
return population_vector_[index];
}
int Population::select_parent() {
/* This method is used to randomly select a individual from the population
* to become a parent for the next generation
*/
return rand() % population_vector_.size();
}
void Population::generate_offsprings() {
/* Ths method creates a number of offsprings equal to the number of
* individuals in the population, apply mutation on each on them with
* a given probability and add the resulting offsprings to the population_vector_
*/
std::vector<Individual> offsprings;
for (int i = 0; i < population_vector_.size(); i++) {
int parent1_index = select_parent();
int parent2_index = select_parent();
while (parent1_index == parent2_index) {
parent1_index = select_parent();
parent2_index = select_parent();
}
Individual parent1 = population_vector_[parent1_index];
Individual parent2 = population_vector_[parent2_index];
Individual offspring(parent1, parent2, evaluator_);
offspring.mutate(graph_, mutation_probability_);
offsprings.push_back(offspring);
}
for (Individual &offspring : offsprings) {
population_vector_.push_back(offspring);
}
}
void Population::generate_next_generation() {
/*
* This method selects for the next generation the first n best individuals, where
* n is the initial number of individuals from population
*/
std::vector<Individual> next_generation;
std::sort(population_vector_.begin(), population_vector_.end());
std::reverse(population_vector_.begin(), population_vector_.end());
population_vector_.resize(population_vector_.size()/2);
}