Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- float SimulatedAnnealing::calculateProbability(int currCost, int newCost, int currTemp)
- {
- return powf(2.7182818f, -(float(newCost - currCost) / currTemp));
- }
- void SimulatedAnnealing::launchAlgorithm(Graph graph, float coolingRate, float endTemp)
- {
- srand(time(NULL));
- int currCost = 0;
- int newCost = 0;
- cost = INT_MAX;
- std::vector<int> currPath = randomPath(graph.getCosts().size());
- currCost = calculateCost(graph, currPath);
- int temp = 10000;
- while (temp > endTemp)
- {
- std::vector<int> newPath = currPath;
- //zamiana 2 losowych miast
- int firstCity = rand() % newPath.size();
- int secondCity;
- do
- {
- secondCity = rand() % newPath.size();
- }
- while (firstCity == secondCity);
- std::swap(newPath.at(firstCity), newPath.at(secondCity));
- //przeliczenie nowego kosztu
- newCost = calculateCost(graph, newPath);
- if (newCost < currCost)
- {
- currCost = newCost;
- currPath = newPath;
- if (newCost < cost)
- {
- cost = newCost;
- path = currPath;
- }
- }
- else
- {
- double random = double(rand() / RAND_MAX);
- double probability = calculateProbability(currCost, newCost, temp);
- //sprawdzam gorszy wynik
- if (random < probability)
- {
- path = newPath;
- cost = newCost;
- }
- }
- temp *= coolingRate;
- }
- }
- std::vector<int> SimulatedAnnealing::randomPath(int length)
- {
- std::vector<int> path;
- for (int i = 0; i < length; i++)
- path.push_back(i);
- std::next_permutation(path.begin(), path.end());
- return path;
- }
- int SimulatedAnnealing::calculateCost(Graph graph, std::vector<int> path)
- {
- int cost = 0;
- for (int i = 0; i < path.size() - 1; i++)
- {
- cost += graph.getCosts()[path[i]][path[i + 1]];
- }
- cost += graph.getCosts()[path.size() - 1][0];
- return cost;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement