Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <cmath>
- #include <vector>
- #include <random>
- #include <algorithm>
- // Область допустимых значений
- std::pair Dx = {0, 2}, Dy = {-2, 2};
- // Данная функция
- double Function(std::pair<double, double> X_Y) {
- return sin(X_Y.first) * sin(X_Y.second) / (1 + X_Y.first * X_Y.first + X_Y.second * X_Y.second);
- }
- std::vector<size_t> Roulette(const std::vector<std::pair<double, double>> &Population) {
- double Sum = 0;
- std::vector<size_t> Return;
- Return.reserve(Population.size());
- for (const auto &i : Population)
- Sum += Function(i);
- for (const auto &i : Population)
- Return.emplace_back(Function(i) / Sum * 100);
- return Return;
- }
- // Сортировка по убыванию
- struct SortStruct {
- bool operator() (std::pair<double, double> i, std::pair<double, double> j) {
- return (Function(i) > Function(j));
- }
- } MySortMethod;
- void CrossOver(std::vector<size_t> Vec, std::vector<std::pair<double,double>> &Population) {
- std::vector<std::pair<double, double>> Return;
- for(const auto &i: Population) {
- std::random_device Rand;
- std::mt19937 Mt(Rand());
- std::uniform_real_distribution<double> Dist (0, 100);
- double Probability = Dist(Mt);
- size_t Sum = 0, Index = 0;
- for (size_t j = 0; j < Vec.size(); j++) {
- Sum += Vec[j];
- if (Sum > Probability) {
- Index = j;
- break;
- }
- // Если на последней итерации Sum < Probability
- if (j == Vec.size() - 1)
- Index = -1;
- }
- if (Index != -1) {
- Return.emplace_back(std::make_pair(Population[Index].first, i.second));
- Return.emplace_back(std::make_pair(i.first, Population[Index].second));
- }
- }
- // Сортируем по убыванию
- // дольше, но легче чем 4 раза искать наибольший элемент, исключая результаты предыдущих итераций
- std::sort(Return.begin(), Return.end(), MySortMethod);
- Return.resize(4);
- Population.resize(4);
- Population = Return;
- }
- int main() {
- std::random_device Device;
- std::mt19937 Mt(Device());
- std::vector<std::pair<double, double>> Population;
- Population.reserve(4);
- for (int i = 0; i < 4; i++) {
- std::pair<double, double> Point;
- std::uniform_real_distribution<double> DistX(Dx.first, Dx.second);
- Point.first = DistX(Mt);
- std::uniform_real_distribution<double> DistY(Dy.first, Dy.second);
- Point.second = DistY(Mt);
- Population.emplace_back(Point);
- }
- std::cout << "| № | X | Y | Fit | Max | Average |\n";
- for (size_t i = 0; i < 10; ++i) {
- CrossOver(Roulette(Population), Population);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement