I am trying to understand and implement a solution for the Closest/farthest pair of points
problem.
On https://en.wikipedia.org/wiki/Closest_pair_of_points_problem there is an example of the brute-force approach:
minDist = infinity
for i = 1 to length(P) - 1 do
for j = i + 1 to length(P) do
let p = P[i], q = P[j]
if dist(p, q) < minDist then
minDist = dist(p, q)
closestPair = (p, q)
return closestPair
The thing is that I can't figure a way of doing the same in C++.
I don't want to return anything. I want to store the pair of structs into something that I can later output.
I've commented a mock-up implementation that does not work.
struct punct
{
int x, y;
float distanta(punct z)
{
float dx = z.x - x, dy = z.y - y;
return std::sqrt(dx * dx + dy * dy);
}
};
float min = v->distanta(*(v + 1));
float max = min;
// punct close, far;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
{
if (((v + i)->distanta(*(v + j))) > max)
{
max = ((v + i)->distanta(*(v + j)));
// far = (*(v+i), *(v+j));
}
if (((v + i)->distanta(*(v + j))) < min)
{
min = ((v + i)->distanta(*(v + j)));
// close = (*(v+i), *(v+j));
}
}
cout.precision(4);
cout << min << " " << max;
// cout << far; // this doesn't work;
From these two pieces of code I want to output something like "The farthest two points are (x, y) and (a, b)."
.
Also, how do I handle the case where there are more than one close
or far
pair ? Meaning that there are two or more smallest/largest distances.