Add first part of a working solution

This commit is contained in:
Segcolt 2024-10-12 15:40:21 -03:00
parent 7dbfdde3f1
commit ea8be549a2
3 changed files with 68 additions and 8 deletions

21
main.cpp Normal file
View File

@ -0,0 +1,21 @@
#include <iostream>
#include <vector>
#include "sa.hpp"
int main()
{
int number_of_items = 0;
int capacity = 0;
std::cin >> number_of_items >> capacity;
std::vector<long long> items(number_of_items);
for (auto &i : items) {
std::cin >> i;
}
sa::solution act = sa::solution::simulated_annealing(capacity, items,
1000, 0.99);
}

33
sa.cpp Normal file
View File

@ -0,0 +1,33 @@
#include "sa.hpp"
#include <cmath>
auto sa::solution::simulated_annealing(int cap, const std::vector<long long> &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;
}

22
sa.hpp
View File

@ -1,9 +1,10 @@
#ifndef SIMULATED_ANNEALING_HEADER_12647_H #ifndef SIMULATED_ANNEALING_HEADER_12647_H
#define SIMULATED_ANNEALING_HEADER_12647_H #define SIMULATED_ANNEALING_HEADER_12647_H
#include <vector>
#include <algorithm> #include <algorithm>
#include <iostream>
#include <random> #include <random>
#include <vector>
namespace sa { namespace sa {
@ -30,15 +31,13 @@ class solution {
} }
public: public:
solution() = default;
solution(const std::vector<long long> &items, int capacity): // Gera a solução inicial solution(const std::vector<long long> &items, int capacity): // Gera a solução inicial
items(items), capacity(capacity), fitness(calculate_boxes()) { items(items), gen(std::random_device()()), capacity(capacity),
std::random_device rdevice; fitness(calculate_boxes()) {}
gen.seed(rdevice());
}
solution(const solution &sol):
items(sol.items), gen(sol.gen), capacity(sol.capacity) { // Gera um vizinho da solução
void setneighbor() { // Gera um vizinho da solução
std::uniform_int_distribution<> dist(0, items.size() - 1); std::uniform_int_distribution<> dist(0, items.size() - 1);
int first = dist(gen); int first = dist(gen);
int second = 0; int second = 0;
@ -60,6 +59,13 @@ class solution {
std::swap(capacity, other.capacity); std::swap(capacity, other.capacity);
std::swap(gen, other.gen); 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<long long> &initial,
double alpha, double temp)->solution;
}; };
} // namespace sa } // namespace sa