-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindividual.cpp
More file actions
86 lines (64 loc) · 2.04 KB
/
individual.cpp
File metadata and controls
86 lines (64 loc) · 2.04 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
84
85
#include "individual.h"
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
// constructor
Individual::Individual(int gene_size, string target) :
gene_size_(gene_size), target_(target)
{
// cout << "Creating individual with gene size" << gene_size << endl;
total_fitness_ = 0;
for (int i = 0; i < gene_size_; ++i)
{
// generate random genes initially
char nucleotide_char = 'a' + (rand()%28);
if (nucleotide_char == '{') nucleotide_char = 32; // to generate spaces
if (nucleotide_char == '|') nucleotide_char = 10; // to generate newlines
string nucleotide(1, nucleotide_char); // create string size 1 w/ the character
genes.push_back(nucleotide);
}
// calculate fitness
calcFitness();
}
// print function
const void Individual::print()
{
for (size_t i = 0; i < genes.size(); ++i)
{
cout << genes[i];
}
cout << endl;
}
// mutates the individual's genes based on the rate
void Individual::mutateIndividual(double mut_rate)
{
// cout << "Mutating individual" << endl;
int r;
// mutating the individual nucleotides aka letters
for (int i = 0; i < gene_size_; ++i)
{
r = rand() % 100;
if (r < mut_rate * 100)
{
char nucleotide_char = 'a' + (rand()%28);
if (nucleotide_char == '{') nucleotide_char = 32; // to generate spaces
if (nucleotide_char == '|') nucleotide_char = 10; // to generate newlines
string nucleotide(1, nucleotide_char); // create string size 1 w/ the character
genes[i] = nucleotide;
// genes[i] = "M";
}
}
calcFitness(); // update fitness
}
// calculates fitness defined as distance from the actual target string
void Individual::calcFitness()
{
total_fitness_ = 0;
for (size_t i = 0; i < genes.size(); i++)
{
// compare char values at ith index and add up distances
total_fitness_ += abs(target_.at(i) - genes[i][0]);
}
}