GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
SinglePointCrossover.h
Go to the documentation of this file.
1#ifndef SINGLE_POINT_CROSSOVER_H
2#define SINGLE_POINT_CROSSOVER_H
3
4#pragma once
5
6#include "Crossover.h"
7#include "core/Individual.h"
8#include <stdexcept>
9#include <random>
10#include <utility>
11#include <algorithm>
12
13namespace galib {
14
23 template <typename GeneType>
24 class SinglePointCrossover : public Crossover<GeneType> {
25 public:
27
35 std::pair<Individual<GeneType>, Individual<GeneType>> crossover (
36 const Individual<GeneType>& parent1, const Individual<GeneType>& parent2) override {
37
38 const std::vector<GeneType>& parent1_genotype = parent1.getGenotype();
39 const std::vector<GeneType>& parent2_genotype = parent2.getGenotype();
40
41 if (parent1_genotype.size() != parent2_genotype.size()) {
42 throw std::invalid_argument("Parents must have the same genotype length for crossover.");
43 }
44 std::size_t genotype_size = parent1_genotype.size();
45
46 Individual<GeneType> child1 = parent1;
47 Individual<GeneType> child2 = parent2;
48
49 if (genotype_size > 1) {
50 thread_local static std::random_device rd;
51 thread_local static std::mt19937 gen(rd());
52
53 std::uniform_int_distribution<std::size_t> distribution(1, genotype_size - 1);
54 std::size_t crossover_point = distribution(gen);
55
56 std::vector<GeneType>& child1_genotype = child1.getGenotype();
57 std::vector<GeneType>& child2_genotype = child2.getGenotype();
58
59 std::swap_ranges(
60 child1_genotype.begin() + crossover_point,
61 child1_genotype.end(),
62 child2_genotype.begin() + crossover_point
63 );
64 }
65 return std::make_pair(child1, child2);
66 }
67 };
68}
69
70#endif // SINGLE_POINT_CROSSOVER_H
Interface for crossover (recombination) operators.
Definition Crossover.h:20
Represents a single candidate solution in the population.
Definition Individual.h:23
std::vector< GeneType > & getGenotype()
Returns a reference to the genotype vector.
Definition Individual.h:53
Performs traditional single-point crossover.
std::pair< Individual< GeneType >, Individual< GeneType > > crossover(const Individual< GeneType > &parent1, const Individual< GeneType > &parent2) override
Swaps genotype segments at a random crossover point.