-
Notifications
You must be signed in to change notification settings - Fork 0
/
population.h
67 lines (52 loc) · 1.56 KB
/
population.h
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
#pragma once
#include <vector>
#include <random>
#include <algorithm>
#include <iostream>
template<class Specimen>
class Population {
public:
Population() : specimens(POPULATION_SIZE) {}
void update_fitness() {
for (Specimen& s : specimens) {
s.update_fitness();
}
}
void sort_by_fitness() {
std::sort(specimens.begin(), specimens.end());
}
void print_best() {
std::cout << "Best: " << specimens.front().to_s() << std::endl;
}
bool has_ideal_specimen() {
return specimens.front().is_ideal();
}
void mate() {
std::vector<Specimen> next_generation(POPULATION_SIZE);
size_t num_elites = (size_t)(ELITISM_RATE * POPULATION_SIZE);
for (size_t i = 0; i < num_elites; i++) {
next_generation[i] = specimens[i];
}
for (size_t i = num_elites; i < POPULATION_SIZE; i++) {
const Specimen& mother = random_specimen();
const Specimen& father = random_specimen();
Specimen child = mother.child_with(father);
static std::default_random_engine generator;
static std::bernoulli_distribution distribution(MUTATION_RATE);
bool should_mutate = distribution(generator);
if (should_mutate) {
child.mutate();
}
next_generation[i] = child;
}
specimens.swap(next_generation);
}
private:
std::vector<Specimen> specimens;
const Specimen& random_specimen() {
return specimens[std::rand() % specimens.size()];
}
static constexpr double ELITISM_RATE = 0.1;
static constexpr double MUTATION_RATE = 0.25;
static constexpr size_t POPULATION_SIZE = 2048;
};