37 lines
853 B
C++
37 lines
853 B
C++
#include "sa.hpp"
|
|
#include <cmath>
|
|
|
|
auto sa::solution::simulated_annealing(int capacity, const std::vector<long long> &items,
|
|
const double alpha, double temp,
|
|
const double temp_min)->sa::solution
|
|
{
|
|
sa::solution best(items, capacity);
|
|
|
|
sa::solution prev = best;
|
|
std::random_device rdevice;
|
|
std::default_random_engine eng(rdevice());
|
|
std::uniform_real_distribution<> rand(0, 1);
|
|
|
|
int iteration = 0;
|
|
|
|
while (temp > temp_min) {
|
|
iteration++;
|
|
sa::solution neighbor(prev, iteration);
|
|
neighbor.setneighbor();
|
|
|
|
int diff = neighbor.fitness - prev.fitness;
|
|
if (diff <= 0 || std::exp(-diff / temp) > rand(eng)) {
|
|
swap(prev, neighbor);
|
|
}
|
|
|
|
temp *= alpha;
|
|
|
|
if (prev.fitness < best.fitness) {
|
|
best = prev;
|
|
}
|
|
}
|
|
|
|
best.setiterations(iteration);
|
|
return best;
|
|
}
|