Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1.  
  2. float SimulatedAnnealing::calculateProbability(int currCost, int newCost, int currTemp)
  3. {
  4.     return powf(2.7182818f, -(float(newCost - currCost) / currTemp));
  5. }
  6.  
  7. void SimulatedAnnealing::launchAlgorithm(Graph graph, float coolingRate, float endTemp)
  8. {
  9.     srand(time(NULL));
  10.     int currCost = 0;
  11.     int newCost = 0;
  12.     cost = INT_MAX;
  13.     std::vector<int> currPath = randomPath(graph.getCosts().size());
  14.     currCost = calculateCost(graph, currPath);
  15.     int temp = 10000;
  16.  
  17.     while (temp > endTemp)
  18.     {
  19.         std::vector<int> newPath = currPath;
  20.         //zamiana 2 losowych miast
  21.         int firstCity = rand() % newPath.size();
  22.         int secondCity;
  23.         do
  24.         {
  25.             secondCity = rand() % newPath.size();
  26.         }
  27.         while (firstCity == secondCity);
  28.         std::swap(newPath.at(firstCity), newPath.at(secondCity));
  29.         //przeliczenie nowego kosztu
  30.         newCost = calculateCost(graph, newPath);
  31.         if (newCost < currCost)
  32.         {
  33.             currCost = newCost;
  34.             currPath = newPath;
  35.  
  36.             if (newCost < cost)
  37.             {
  38.                 cost = newCost;
  39.                 path = currPath;
  40.             }
  41.         }
  42.         else
  43.         {
  44.             double random = double(rand() / RAND_MAX);
  45.             double probability = calculateProbability(currCost, newCost, temp);
  46.             //sprawdzam gorszy wynik
  47.             if (random < probability)
  48.             {
  49.                 path = newPath;
  50.                 cost = newCost;
  51.             }
  52.         }
  53.         temp *= coolingRate;
  54.     }
  55. }
  56.  
  57. std::vector<int> SimulatedAnnealing::randomPath(int length)
  58. {
  59.     std::vector<int> path;
  60.     for (int i = 0; i < length; i++)
  61.         path.push_back(i);
  62.     std::next_permutation(path.begin(), path.end());
  63.     return path;
  64. }
  65.  
  66. int SimulatedAnnealing::calculateCost(Graph graph, std::vector<int> path)
  67. {
  68.     int cost = 0;
  69.     for (int i = 0; i < path.size() - 1; i++)
  70.     {
  71.         cost += graph.getCosts()[path[i]][path[i + 1]];
  72.     }
  73.     cost += graph.getCosts()[path.size() - 1][0];
  74.     return cost;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement