I have to write a program that inputs pairs of points from the user and finds the closest neighbor to each point, using the distance formula.
From the instructions I've been given, I must edit only the main() function and add a nested loop to compare each point, but I'm not sure how to do this.
The instructor has also written a function to overload operator- that returns the distance, which I think I'm supposed to use, somehow.
The output should look something like this:
Example input 1
5 1 1 2 2 3 3 4 4 5 5Example output 1
(1,1) (2,2) (3,3) (4,4) (5,5) (1,1) nearest (2,2) (2,2) nearest (1,1) (3,3) nearest (2,2) (4,4) nearest (3,3) (5,5) nearest (4,4)
This is the main.cpp code:
void displayPoints(vector<Point> &points) {
// Finish
for (int i = 0; i < points.size(); i++) {
cout << points[i] << " ";
}
cout <<endl;
}
void createPointsList(vector<Point> &points) {
int s;
cin >> s;
for (int i = 0; i < s; ++i) {
int x, y;
cin >> x >> y;
points.push_back(Point(x, y));
}
}
int main() {
vector<Point> points;
createPointsList(points);
displayPoints(points);
// Add code to find nearest here
// Hint: will need a nested loop to compare each point with every other point
}
//The overloaded operator is :
// d=√((x2 – x1)² + (y2 – y1)²)
double Point::operator-(const Point& point) const {
return (pow(point.x-x,2) + pow(point.y-y,2)));
}
You could use a nested loop and compare each value with the other.
Need to add an
if-statement to prevent to compare points to itself.In your loop, find the smallest distance and show it for the current Point at the end of the outer loop.
The solution is rather straight forward:
Input and output of this program: