Compare commits

...

2 Commits
master ... E4

Author SHA1 Message Date
decfc1c699 Use the renaming thing that they wanted 2024-09-06 16:33:54 +02:00
0b75e07b1d E3 2024-09-06 16:23:07 +02:00
3 changed files with 45 additions and 2 deletions

View File

@ -116,6 +116,48 @@ void Tour::insertNearest(Point p) {
nearest->next = newNode;
}
Node *findbestNodeTSP(Node *const start, Point &point) {
auto calcHeuristic = [&point](Node *const insertAt) -> double {
double distanceWithNewPoint = insertAt->point.distanceTo(point) +
point.distanceTo(insertAt->next->point);
double originalDistance = insertAt->point.distanceTo(insertAt->next->point);
return distanceWithNewPoint - originalDistance;
};
double optimalH = Q_INFINITY;
Node *optimalNode;
Node *node = start;
do {
double h = calcHeuristic(node);
if (h < optimalH) {
optimalH = h;
optimalNode = node;
}
node = node->next;
} while (node != start);
return optimalNode;
}
void Tour::insertOptimalHeuristic(Point p) {
if (m_startNode == nullptr) {
m_startNode = new Node(p);
m_startNode->next = m_startNode; // Make it cirkular
return;
}
if (m_startNode->next == nullptr) {
auto newNode = new Node(p, m_startNode);
m_startNode->next = newNode;
return;
}
Node *bestNode = findbestNodeTSP(m_startNode, p);
auto *newNode = new Node(p, bestNode->next);
bestNode->next = newNode;
}
void Tour::insertSmallest(Point p) {
if (m_startNode == nullptr) {
m_startNode = new Node(p);

View File

@ -24,6 +24,7 @@ public:
double distance() const;
void insertNearest(Point p);
void insertSmallest(Point p);
void insertOptimalHeuristic(Point p);
private:
Node* m_startNode;

View File

@ -49,7 +49,7 @@ int main(int argc, char *argv[]) {
auto timeStart = std::chrono::high_resolution_clock::now();
while (input >> x >> y) {
Point p(x, y);
tour.insertNearest(p);
tour.insertOptimalHeuristic(p);
//uncomment the 4 lines below to animate
//tour.draw(scene);
//std::chrono::milliseconds dura(50);