-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathExercise08_08.java
67 lines (59 loc) · 2.03 KB
/
Exercise08_08.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package ch_08;
/**
* **8.8 (All closest pairs of points) Revise Listing 8.3,
* FindNearestPoints.java, to display all closest pairs of points with the same
* minimum distance.
*
* Here is a sample run:
*
* Enter the number of points: 8 Enter 8 points: 0 0 1 1 -1 -1 2 2 -2 -2 -3 -3
* -4 -4 5 5
*
* The closest two points are (0.0, 0.0) and (1.0, 1.0)
*
* The closest two points are (0.0, 0.0) and (-1.0, -1.0)
*
* The closest two points are (1.0, 1.0) and (2.0, 2.0)
*
* The closest two points are (-1.0, -1.0) and (-2.0, -2.0)
*
* The closest two points are (-2.0, -2.0) and (-3.0, -3.0)
*
* The closest two points are (-3.0, -3.0) and (-4.0, -4.0)
*
* Their distance is 1.4142135623730951
*
*/
public class Exercise08_08 {
private static int[][] points;
static double shortestDist;
static {
points = new int[][] { { 0, 0 }, { 1, 1 }, { -1, -1 }, { 2, 2 }, { -2, -2 }, { -3, -3 }, { -4, -4 }, { 5, 5 } };
}
public static void main(String[] args) {
shortestDist = distance(points[0][0], points[0][1], points[1][0], points[1][1]); // Initialize
// Find shortest Distance
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double shrtTest = distance(points[i][0], points[i][1], points[j][0], points[j][1]); // Find distance
if (shrtTest < shortestDist) {
shortestDist = shrtTest;
}
}
}
// Print points with distance between equal to shortest distance
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double d = distance(points[i][0], points[i][1], points[j][0], points[j][1]); // check distance
if (d == shortestDist) {
System.out.println("The closest two points are (" + points[i][0] + "," + points[i][1] + ") and ("
+ points[j][0] + ", " + points[j][1] + ")");
}
}
}
System.out.print("Their distance is " + shortestDist);
}
public static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}