Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "annealing.h"
- double cooling_temperature=0.9999;
- double initial_temperature=1000.0;
- double minimal_temperature=0.0001;
- unsigned int iterations=100;
- double current_temperature;
- double current_length;
- double best_length;
- int* current_path;
- int* best_path;
- int get_iterations() { return iterations; }
- double get_minimal_temperature() { return minimal_temperature; }
- double get_initial_temperature() { return initial_temperature; }
- double get_cooling_temperature() { return cooling_temperature; }
- void random_swap(int numberOfCities)
- {
- int a = std::rand() % numberOfCities;
- int b = std::rand() % numberOfCities;
- while (a == b) b = std::rand() % numberOfCities;
- current_path = best_path;
- int temporary = current_path[a];
- current_path[a] = current_path[b];
- current_path[b] = temporary;
- }
- double path_length(int** matrix,int* path, int numberOfCities)
- {
- int len=0;
- int vertex1, vertex2;
- for(int i = 0; i<numberOfCities-1;i++)
- {
- vertex1 = path[i];
- vertex2 = path[i+1];
- len+=matrix[vertex1][vertex2];
- }
- len+=matrix[vertex2][path[0]];
- return len;
- }
- double probability()
- {
- double power = -((current_length - best_length) / current_temperature);
- return pow(M_E, power);
- }
- void annealing(int** matrix,int numberOfCities)
- {
- current_temperature = initial_temperature;
- current_path = new int[numberOfCities];
- best_path = new int[numberOfCities];
- for (unsigned int i = 0; i <numberOfCities; i++)
- current_path[i] = i;
- current_length = path_length(matrix,current_path, numberOfCities);
- for (size_t i = 0; i < numberOfCities; i++)
- best_path[i] = current_path[i];
- best_length = current_length;
- srand((unsigned int)time(NULL));
- while (current_temperature > minimal_temperature)
- {
- for (int j = 0; j < iterations; j++)
- {
- random_swap(numberOfCities);
- current_length = path_length(matrix,current_path,numberOfCities);
- if (current_length < best_length || ((double)rand() / (double)RAND_MAX) < probability())
- {
- best_path = current_path;
- best_length = current_length;
- // for (unsigned int i = 0; i < numberOfCities; i++)
- // cout << " " << best_path[i];
- // cout << " " << best_path[0] << " | " << best_length << endl;
- }
- }
- current_temperature *= cooling_temperature;
- }
- for (unsigned int i = 0; i < numberOfCities; i++)
- cout << " " << best_path[i];
- cout << " " << best_path[0] << " | " << best_length << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement