#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;
const string TARGET = "HELLO WORLD";
const int POPULATION_SIZE = 100;
const int STRING_LENGTH = TARGET.length();
const double MUTATION_RATE = 0.01;
const int MAX_GENERATIONS = 1000;
// Function to generate a random candidate string
string generateRandomString() {
string result;
for (int i = 0; i < STRING_LENGTH; ++i) {
result += static_cast<char>(rand() % 26 + 'A');
}
return result;
}
// Function to calculate fitness of a candidate string
int calculateFitness(const string& candidate) {
int fitness = 0;
for (int i = 0; i < STRING_LENGTH; ++i) {
if (candidate[i] == TARGET[i]) {
++fitness;
}
}
return fitness;
}
// Function to perform crossover between two parent strings
string crossover(const string& parent1, const string& parent2) {
string child;
int crossoverPoint = rand() % STRING_LENGTH;
for (int i = 0; i < STRING_LENGTH; ++i) {
child += (i < crossoverPoint) ? parent1[i] : parent2[i];
}
return child;
}
// Function to perform mutation on a candidate string
void mutate(string& candidate) {
for (int i = 0; i < STRING_LENGTH; ++i) {
if (static_cast<double>(rand()) / RAND_MAX < MUTATION_RATE) {
candidate[i] = static_cast<char>(rand() % 26 + 'A');
}
}
}
// Main Genetic Algorithm function
void geneticAlgorithm() {
vector<string> population(POPULATION_SIZE);
vector<int> fitness(POPULATION_SIZE);
// Initialize random seed
srand(static_cast<unsigned int>(time(nullptr)));
// Generate initial population
for (int i = 0; i < POPULATION_SIZE; ++i) {
population[i] = generateRandomString();
}
int generation = 0;
while (generation < MAX_GENERATIONS) {
// Calculate fitness for the population
int bestFitness = 0;
string bestCandidate;
for (int i = 0; i < POPULATION_SIZE; ++i) {
fitness[i] = calculateFitness(population[i]);
if (fitness[i] > bestFitness) {
bestFitness = fitness[i];
bestCandidate = population[i];
}
}
// Output the best candidate
cout << "Generation " << generation << ": " << bestCandidate << " (Fitness: " << bestFitness << ")" << endl;
if (bestFitness == STRING_LENGTH) {
cout << "Target string reached!" << endl;
break;
}
// Generate new population
vector<string> newPopulation;
while (newPopulation.size() < POPULATION_SIZE) {
// Select parents
int parent1Index = rand() % POPULATION_SIZE;
int parent2Index = rand() % POPULATION_SIZE;
// Perform crossover and mutation
string child = crossover(population[parent1Index], population[parent2Index]);
mutate(child);
newPopulation.push_back(child);
}
population = newPopulation;
++generation;
}
}
int main() {
geneticAlgorithm();
return 0;
}