dignea  1.0.0
Diverse Instance Generator with Novelty Search and Evolutionary Algorithms
ReplaceWorst.h
Go to the documentation of this file.
1 
11 #ifndef DIGNEA_REPLACEWORST_H
12 #define DIGNEA_REPLACEWORST_H
13 
14 #include <dignea/core/Replacement.h>
17 #include <dignea/utilities/exceptions/NotImplemented.h>
18 
19 #include <string>
20 
21 using namespace std;
22 
29 template <class S>
30 class ReplaceWorst : public Replacement<S> {
31  public:
32  ReplaceWorst() = default;
33 
34  virtual ~ReplaceWorst() = default;
35 
36  vector<S> replace(vector<S> &vector1, vector<S> &vector2) override;
37 
38  vector<S> replace(vector<S> &vector1, const S &solution,
39  const int &position) override;
40 
41  string getName() const override { return "Replace Worst"; }
42 };
43 
52 template <class S>
53 vector<S> ReplaceWorst<S>::replace(vector<S> &population,
54  vector<S> &offspring) {
55  if (offspring.empty() || offspring.size() != 1) {
56  std::string what = " offspring.size = " + to_string(offspring.size());
57  throw(runtime_error("Replace Worst " + what));
58  }
59  if (population.empty()) {
60  std::string what = " population is empty";
61  throw(runtime_error("Replace Worst " + what));
62  }
63  // Buscamos los dos mejores fitness
64  sortByFitness(population);
65  int worstSIndex = population.size() - 1;
66  if (cmpByFitness(population[worstSIndex], offspring[0])) {
67  population[worstSIndex] = offspring[0];
68  }
69  return population;
70 }
71 
81 template <class S>
82 vector<S> ReplaceWorst<S>::replace(vector<S> &vector1, const S &solution,
83  const int &position) {
84  string where =
85  "Replace with position not allowed in Replace Worst replacement";
86  throw NotImplemented(where);
87 }
88 
89 #endif // DIGNEA_REPLACEWORST_H
int cmpByFitness(const S &ind1, const S &ind2)
Compares two individuals by their fitness.
Definition: Comparator.h:39
void sortByFitness(vector< S > &population)
Sorts the population by fitness in descending order.
Definition: Sorter.h:69
Replacement procedure which replaces the worst individual in the population with the new offspring.
Definition: ReplaceWorst.h:30
vector< S > replace(vector< S > &vector1, vector< S > &vector2) override
Replaces the worst individual in the population for the best in offspring. Offspring must be of size ...
Definition: ReplaceWorst.h:53
Replacement skeleton operator.
Definition: Replacement.h:16