Skip to content

Instantly share code, notes, and snippets.

@alekseyl1992
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alekseyl1992/9099a3c0210b7656bc68 to your computer and use it in GitHub Desktop.
Save alekseyl1992/9099a3c0210b7656bc68 to your computer and use it in GitHub Desktop.
using Generation = std::vector<Genome>;
constexpr int buildingSize = 100;
Genome createGenome() {
Genome genome;
int currentFloor = 0;
do {
currentFloor = rand() % (buildingSize - currentFloor) + currentFloor + 1;
genome.push_back(currentFloor);
} while (currentFloor != buildingSize);
return genome;
}
int fitness(Genome& genome) {
int actualMax = rand() % buildingSize;
int count = 0;
int lastFloor = 0;
for (int floor: genome) {
if (floor < actualMax)
++count;
else
return count + (actualMax - lastFloor) + 1;
lastFloor = floor;
}
return count;
}
Generation createGeneration() {
constexpr int generationSize = 100;
Generation generation;
for (int i = 0; i < generationSize; ++i) {
Genome genome = createGenome();
generation.emplace_back(genome);
}
return generation;
}
Genome crossover(Genome& a, Genome& b) {
Genome result;
for (int gen: a)
if (rand() % 2)
result.push_back(gen);
for (int gen: b)
if (rand() % 2)
result.push_back(gen);
std::sort(result.begin(), result.end());
return result;
}
void mutate(Genome& genome) {
int count = genome.size() / 10;
for (int i = 0; i < count; ++i) {
int id = rand() % genome.size();
genome[id] = rand() % buildingSize;
}
std::sort(genome.begin(), genome.end());
}
void output(Genome& genome) {
int count = std::min(10, genome.size());
for (int i = 0; i < count; ++i)
std::cout << genome[i] << " ";
std::cout << std::endl;
}
int main() {
Generation generation = createGeneration();
for (int genId = 0; genId < INT_MAX; ++genId) {
for (Genome& genome: generation) {
genome.fitness = fitness(genome);
}
std::sort(generation.begin(), generation.end(), [](Genome& a, Genome& b) {
return a.fitness > b.fitness;
});
output(generation[0]);
int crossOversCount = generation.size() / 2;
int generationSize = generation.size();
for (int i = 0; i < crossOversCount; ++i) {
Genome &a = generation[rand() % (generationSize / 2)];
Genome &b = generation[rand() % (generationSize / 2)];
generation[generationSize - i - 1] = crossover(a, b);
}
int mutationsCount = generation.size() / 20;
for (int i = 0; i < mutationsCount; ++i) {
Genome &a = generation[rand() % generationSize];
mutate(a);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment