GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
UniformCrossover.h
Go to the documentation of this file.
1#ifndef UNIFORM_CROSSOVER_H
2#define UNIFORM_CROSSOVER_H
3
4#pragma once
5
6#include "Crossover.h"
7#include <random>
8#include <stdexcept>
9#include <utility>
10
11namespace galib {
12
21 template <typename GeneType>
22 class UniformCrossover : public Crossover<GeneType> {
23 public:
31 std::pair<Individual<GeneType>, Individual<GeneType>>
33 const Individual<GeneType>& parent2) override {
34
35 if (parent1.size() != parent2.size()) {
36 throw std::invalid_argument("Parents must have the same genotype size");
37 }
38
39 thread_local static std::random_device rd;
40 thread_local static std::mt19937 gen(rd());
41 thread_local static std::bernoulli_distribution pick_first(0.5);
42
43 Individual<GeneType> child1(parent1.size());
44 Individual<GeneType> child2(parent2.size());
45
46 const auto& g1 = parent1.getGenotype();
47 const auto& g2 = parent2.getGenotype();
48
49 auto& c1 = child1.getGenotype();
50 auto& c2 = child2.getGenotype();
51
52 for (std::size_t i = 0; i < g1.size(); ++i) {
53 if (pick_first(gen)) {
54 c1[i] = g1[i];
55 c2[i] = g2[i];
56 } else {
57 c1[i] = g2[i];
58 c2[i] = g1[i];
59 }
60 }
61
62 return {child1, child2};
63 }
64 };
65
66}
67
68#endif // UNIFORM_CROSSOVER_Hдавай так рідмі потім перепише спочатку
Interface for crossover (recombination) operators.
Definition Crossover.h:20
Represents a single candidate solution in the population.
Definition Individual.h:23
std::size_t size() const
Returns the number of genes in the genotype.
Definition Individual.h:47
std::vector< GeneType > & getGenotype()
Returns a reference to the genotype vector.
Definition Individual.h:53
Performs uniform crossover.
std::pair< Individual< GeneType >, Individual< GeneType > > crossover(const Individual< GeneType > &parent1, const Individual< GeneType > &parent2) override
Randomly picks genes from either parent at each position.