Last active
December 20, 2015 07:49
-
-
Save agasiev/6095890 to your computer and use it in GitHub Desktop.
String generation with genetic algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <cstdlib> | |
#include <string> | |
using namespace std; | |
string result = "hello world!"; | |
int closeness(const string & a) { | |
int res = result.size(); | |
for (int i = 0; i < result.size(); i++) { | |
if (result[i] != a[i]) res--; | |
} | |
return res; | |
} | |
bool comp(const string & a, const string & b) { | |
return (closeness(a) < closeness(b)); | |
} | |
int main(int, char**) { | |
string alphabet = "abcdefghijklmnopqrstuvwxyz !"; | |
int len = alphabet.length(); | |
int start_size = 20; | |
vector<string> population(start_size); | |
for (int i = 0; i < population.size(); ++i) { | |
for (int j = 0; j < result.size(); ++j) { | |
population[i].push_back(alphabet[rand() % len]); | |
} | |
} | |
int cnt = 0; | |
while (true) { | |
cnt++; | |
// crossing | |
for (int i = 0; i < start_size; ++i) { | |
int m = rand() % population.size(); | |
int n = rand() % population.size(); | |
int pivot = rand() % (result.size() - 1); | |
string new_subject = population[m].substr(0, pivot) + population[n].substr(pivot, result.size()); | |
population.push_back(new_subject); | |
} | |
// mutation | |
for (int i = 0; i < population.size(); ++i) { | |
if (rand() % 100 <= 5) { | |
population[i][rand() % (population[i].length())] = alphabet[rand() % len]; | |
} | |
} | |
// selection | |
std::sort(population.rbegin(), population.rend(), comp); | |
population.erase(population.begin() + start_size, population.end()); | |
cout << population[0] << endl; | |
if (closeness(population[0]) == result.size()) | |
break; | |
} | |
cout << "Generation count: " << cnt << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment