#include <set>
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cfloat>
typedef std::array<double, 3> Point3D;
double squareDistancePoints(const Point3D& a, const Point3D& b)
{
double squareSum = 0;
for (size_t i = 0; i < a.size(); ++i)
squareSum += pow(a[i] - b[i], 2);
return squareSum;
}
int main(int argc, char **argv)
{
std::vector<Point3D> orderedMatrix;
// Sortierte Punkte eines Rechtecks
orderedMatrix.push_back({ 0, 0, 0 });
orderedMatrix.push_back({ 50, 0, 0 });
orderedMatrix.push_back({ 100, 0, 0 });
orderedMatrix.push_back({ 100, 50, 0 });
orderedMatrix.push_back({ 100, 100, 0 });
orderedMatrix.push_back({ 50, 100, 0 });
orderedMatrix.push_back({ 0, 100, 0 });
orderedMatrix.push_back({ 0, 50, 0 });
// Unsortierte Punkte erzeugen (einfach zufällig durcheinandergeworfen)
std::vector<Point3D> matrix = orderedMatrix;
for (size_t i = 0; i < matrix.size(); ++i)
std::swap(matrix[i], matrix[rand() % matrix.size()]);
// Duplikate entfernen
// (würde das nach der Sortierung nicht besser passen?
// Außerdem ein bitweiser Vergleich von double-Werten?)
std::set<Point3D> set(matrix.begin(), matrix.end());
matrix.erase(
std::remove_if(matrix.begin(), matrix.end(),
[&set](const Point3D& item) {return !set.erase(item); }),
matrix.end());
// Vorher
std::cout << "Before: " << std::endl;
for (const auto& p : matrix)
std::cout << p[0] << " / " << p[1] << " / " << p[2] << std::endl;
// Sortieren
for (auto it = matrix.begin(); it != matrix.end(); ++it)
{
std::cout << "START "
<< it->at(0) << " / "
<< it->at(1) << " / "
<< it->at(2) << std::endl;
auto bestIt = matrix.end();
double bestSquareDistance = DBL_MAX;
for (auto nextIt = it + 1; nextIt != matrix.end(); ++nextIt)
{
const auto squareDistance = squareDistancePoints(*it, *nextIt);
std::cout << " TRY "
<< nextIt->at(0) << " / "
<< nextIt->at(1) << " / "
<< nextIt->at(2) << " d=" << sqrt(squareDistance) << std::endl;
if (squareDistance < bestSquareDistance)
{
bestSquareDistance = squareDistance;
bestIt = nextIt;
}
}
if (bestIt != matrix.end())
{
std::cout << " BEST "
<< bestIt->at(0) << " / "
<< bestIt->at(1) << " / "
<< bestIt->at(2) << " d=" << sqrt(bestSquareDistance) << std::endl;
std::swap(*(it + 1), *bestIt);
}
}
// Nachher
std::cout << "After: " << std::endl;
for (const auto& p : matrix)
std::cout << p[0] << " / " << p[1] << " / " << p[2] << std::endl;
return 0;
}