diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..e1270a1 --- /dev/null +++ b/main.cpp @@ -0,0 +1,21 @@ +#include +#include + +#include "sa.hpp" + +int main() +{ + int number_of_items = 0; + int capacity = 0; + std::cin >> number_of_items >> capacity; + + std::vector items(number_of_items); + for (auto &i : items) { + std::cin >> i; + } + + sa::solution act = sa::solution::simulated_annealing(capacity, items, + 1000, 0.99); + + +} diff --git a/sa.cpp b/sa.cpp new file mode 100644 index 0000000..e500f05 --- /dev/null +++ b/sa.cpp @@ -0,0 +1,33 @@ +#include "sa.hpp" +#include + +auto sa::solution::simulated_annealing(int cap, const std::vector &initial, + const double alpha, double temp)->sa::solution +{ + sa::solution best(initial, cap); + best.randomize(); + + sa::solution prev = best; + std::random_device rdevice; + std::default_random_engine eng(rdevice()); + std::uniform_real_distribution<> rand(0, 1); + + const double temp_min = 0.30; + while (temp < temp_min) { + sa::solution neighbor(prev); + neighbor.setneighbor(); + + int diff = prev.fitness - neighbor.fitness; + if (diff <= 0 || std::exp(-diff / temp) > rand(eng)) { + prev.swap(neighbor); + } + + temp *= alpha; + + if (prev.fitness < best.fitness) { + best = prev; + } + } + + return best; +} diff --git a/sa.hpp b/sa.hpp index f375714..289a58b 100644 --- a/sa.hpp +++ b/sa.hpp @@ -1,9 +1,10 @@ #ifndef SIMULATED_ANNEALING_HEADER_12647_H #define SIMULATED_ANNEALING_HEADER_12647_H -#include #include +#include #include +#include namespace sa { @@ -30,15 +31,13 @@ class solution { } public: + solution() = default; + solution(const std::vector &items, int capacity): // Gera a solução inicial - items(items), capacity(capacity), fitness(calculate_boxes()) { - std::random_device rdevice; - gen.seed(rdevice()); - } - - solution(const solution &sol): - items(sol.items), gen(sol.gen), capacity(sol.capacity) { // Gera um vizinho da solução + items(items), gen(std::random_device()()), capacity(capacity), + fitness(calculate_boxes()) {} + void setneighbor() { // Gera um vizinho da solução std::uniform_int_distribution<> dist(0, items.size() - 1); int first = dist(gen); int second = 0; @@ -60,6 +59,13 @@ class solution { std::swap(capacity, other.capacity); std::swap(gen, other.gen); } + + void print_sol() { + std::cout << "Número de caixas: " << fitness << '\n'; + } + + static auto simulated_annealing(int cap, const std::vector &initial, + double alpha, double temp)->solution; }; } // namespace sa