Skip to content

Instantly share code, notes, and snippets.

@agasiev
Last active December 20, 2015 07:49
Show Gist options
  • Save agasiev/6095890 to your computer and use it in GitHub Desktop.
Save agasiev/6095890 to your computer and use it in GitHub Desktop.
String generation with genetic algorithm.
#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