OptimisationProblem/GeneticAlgorithm.cpp

64 lines
1.6 KiB
C++
Raw Normal View History

2023-07-17 00:19:10 +02:00
#include "GeneticAlgorithm.h"
#include <iostream>
#include <vector>
Solution* GeneticAlgorithm::algorithm()
{
std::cout << "Running genetic algorithm\n";
Solution* best = (*(this->population))[0];
float bestFitness = this->fitness(best);
int nPop = this->population->size();
for (int gen = 0; gen < this->generations; gen++)
{
std::cout << "Generation " << gen << "\n";
std::cout << "Population size: " << nPop << "\n";
// Fitness
std::vector<float> scores {};
for (Solution* individual : *(this->population))
{
//individual->print();
float fitness = this->fitness(individual);
scores.push_back(fitness);
if (fitness > bestFitness)
{
best = individual;
bestFitness = fitness;
}
}
// Selection
Solutions* children = new Solutions {};
for (int i = 0; i < nPop; i += 2)
{
Solution* p1 = this->selection(this->population, &scores);
Solution* p2 = this->selection(this->population, &scores);
std::cout << "Selected parents 1 and 2 \n";
if (p1 == nullptr || p2 == nullptr)
throw std::runtime_error("Failed to do selection");
Solution* c1 = NULL;
Solution* c2 = NULL;
// Crossover
std::cout << "Doing crossover\n";
this->crossover(this->rCross, p1, p2, &c1, &c2);
if (c1 == nullptr || c2 == nullptr)
throw std::runtime_error("Failed to do crossover");
// Mutation
std::cout << "Mutating c1\n";
this->mutate(c1, rMut);
std::cout << "Mutating c2\n";
this->mutate(c2, rMut);
children->push_back(c1);
children->push_back(c2);
}
this->population = children;
}
return best;
}