Problem

(Points nearest to each other) Listing 8.3 gives a program that finds two points in a two-...

(Points nearest to each other) Listing 8.3 gives a program that finds two points in a two-dimensional space nearest to each other. Revise the program so that it finds two points in a three-dimensional space nearest to each other. Use a two-dimensional array to represent the points. Test the program using the following points:

double[][] points = {{-1, 0, 3}, {-1, -1, -1}, {4, 1, 1},

{2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2},

{5.5, 4, -0.5}};

The formula for computing the distance between two points (x1, y1, z1) and (x2, y2, z2) is

LISTING 1 FindNearestPoints.java

1 import java.util.Scanner;

2

3 public class FindNearestPoints {

4 public static void main(String[] args) {

5 Scanner input = new Scanner(System.in);

6 System.out.print("Enter the number of points: ");

7 int numberOfPoints = input.nextInt();

8

9 // Create an array to store points

10 double[][] points = new double[numberOfPoints][2];

11 System.out.print("Enter " + numberOfPoints + " points: ");

12 for (int i = 0; i

13 points[i][0] = input.nextDouble();

14 points[i][1] = input.nextDouble();

15 }

16

17 // p1 and p2 are the indices in the points' array

18 int p1 = 0, p2 = 1; // Initial two points

19 double shortestDistance = distance(points[p1][0], points[p1][1],

20 points[p2][0], points[p2][1]); // Initialize shortestDistance

21

22 // Compute distance for every two points

23 for (int i = 0; i

24 for (int j = i + 1; j

25 double distance = distance(points[i][0], points[i][1],

26 points[j][0], points[j][1]); // Find distance

27

28 if (shortestDistance > distance) {

29 p1 = i; // Update p1

30 p2 = j; // Update p2

31 shortestDistance = distance; // Update shortestDistance

32 }

33 }

34 }

35

36 // Display result

37 System.out.println("The closest two points are " +

38 "(" + points[p1][0] + ", " + points[p1][1] + ") and (" +

39 points[p2][0] + ", " + points[p2][1] + ")");

40 }

41

42 /** Compute the distance between two points (x1, y1) and (x2, y2)*/

43 public static double distance(

44 double x1, double y1, double x2, double y2) {

45 return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

46 }

47 }

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT