GALib-Parallel
Header-only C++ library for parallel evolutionary algorithms
Loading...
Searching...
No Matches
BestNeighborSelection.h
Go to the documentation of this file.
1#ifndef BEST_NEIGHBOR_SELECTION_H
2#define BEST_NEIGHBOR_SELECTION_H
3
4#pragma once
5
7#include <stdexcept>
8
9namespace galib {
10
19template <typename GeneType>
20class BestNeighborSelection : public LocalSelection<GeneType> {
21public:
34 const Population<GeneType>& population,
35 std::size_t row,
36 std::size_t col,
37 std::size_t rows,
38 std::size_t cols
39 ) const override {
40 if (rows == 0 || cols == 0) {
41 throw std::invalid_argument("BestNeighborSelection requires non-zero grid dimensions.");
42 }
43
44 const std::size_t up = (row == 0) ? rows - 1 : row - 1;
45 const std::size_t down = (row + 1) % rows;
46 const std::size_t left = (col == 0) ? cols - 1 : col - 1;
47 const std::size_t right = (col + 1) % cols;
48
49 const Individual<GeneType>* best = &population[up * cols + col];
50
51 const std::size_t candidates[] = {
52 down * cols + col,
53 row * cols + left,
54 row * cols + right
55 };
56
57 for (const std::size_t idx : candidates) {
58 const Individual<GeneType>& candidate = population[idx];
59 if (candidate.getFitness() < best->getFitness()) {
60 best = &candidate;
61 }
62 }
63
64 return *best;
65 }
66};
67
68} // namespace galib
69
70#endif // BEST_NEIGHBOR_SELECTION_H
Selects the fittest direct neighbour of a cell in a cellular grid.
const Individual< GeneType > & select(const Population< GeneType > &population, std::size_t row, std::size_t col, std::size_t rows, std::size_t cols) const override
Returns the best direct neighbour of the specified cell.
Represents a single candidate solution in the population.
Definition Individual.h:23
double getFitness() const
Gets the current fitness score.
Definition Individual.h:77
Abstract interface for neighbourhood-based parent selection in a cellular GA.
A container for a group of individuals in the genetic algorithm.
Definition Population.h:24