GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
TournamentSelection.h
Go to the documentation of this file.
1#ifndef TOURNAMENT_SELECTION_H
2#define TOURNAMENT_SELECTION_H
3
4#pragma once
5
6#include "Selection.h"
7#include <random>
8#include <algorithm>
9#include <stdexcept>
10#include <cstddef>
11
12namespace galib {
13
22 template <typename GeneType>
23 class TournamentSelection : public Selection<GeneType> {
24 private:
25 std::size_t tournament_size_m;
26 public:
32 explicit TournamentSelection(size_t tournament_size) : tournament_size_m(tournament_size) {
33 if (tournament_size_m == 0) {
34 throw std::invalid_argument("Tournament size must be at least 1.");
35 }
36 }
37
38 std::size_t getTournamentSize() const { return tournament_size_m; }
39
45 const Individual<GeneType>& select(const Population<GeneType>& population) override {
46
47 thread_local static std::random_device rd;
48 thread_local static std::mt19937 gen(rd());
49
50 std::size_t pop_size = population.size();
51 std::uniform_int_distribution<std::size_t> distribution(0, pop_size - 1);
52
53 const Individual<GeneType>* winner = &population[distribution(gen)];
54
55 for (std::size_t i = 1; i < tournament_size_m; ++i) {
56 const Individual<GeneType>& candidate = population[distribution(gen)];
57
58 if (candidate.getFitness() < winner->getFitness()) {
59 winner = &candidate;
60 }
61 }
62 return *winner;
63 }
64 };
65
66}
67
68#endif // TOURNAMENT_SELECTION_H
Represents a single candidate solution in the population.
Definition Individual.h:23
double getFitness() const
Gets the current fitness score.
Definition Individual.h:77
A container for a group of individuals in the genetic algorithm.
Definition Population.h:24
std::size_t size() const
Returns the total number of individuals in the population.
Definition Population.h:68
Interface for selection operators.
Definition Selection.h:20
Performs k-way tournament selection.
std::size_t getTournamentSize() const
const Individual< GeneType > & select(const Population< GeneType > &population) override
Conducts a tournament and returns the winner.
TournamentSelection(size_t tournament_size)
Constructs the selector.