64.6k views
5 votes
Write a C++ program that inputs n, the number of points, and then n lines with x and y and z giving the coordinates of a point. Find the two points that are closest to each other, and output their coordinates and the distance between them.(You must store the points in an array. Point should be a struct, and the array should hold pointers at Points. The obvious O(n*n) algorithm is fine.)

Example: The output should be "1,1,1 and 1,1,2 are 1 unit apart"

3
1 1 1
1 1 2
1 2 3

1 Answer

4 votes

Final answer:

The C++ program takes the number of points and their coordinates in 3D space to find the two closest points using a struct and pointers. Distances are calculated with the Pythagorean theorem, and the program outputs the closest points and their distance.

Step-by-step explanation:

Program to Find the Closest Pair of Points

This C++ program reads the number of points n, accepts the coordinates of the points in 3D space, and determines the two points that are closest to each other. It utilizes a struct to represent a point and uses an array of pointers to store these points. The program calculates distances using the Pythagorean theorem in three dimensions, where the distance d between two points P1 and P2 is given by:

d = sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2)

The algorithm iterates over all pairs of points, a process with O(n^2) complexity, to find the minimum distance and outputs the coordinates of the closest points and their separation distance.

User Andrei Dobrin
by
8.2k points