Java Reference
In-Depth Information
10 double [][] points = new double [numberOfPoints][ 2 ];
11 System.out.print( "Enter " + numberOfPoints + " points: " );
12 for ( int i = 0 ; i < points.length; i++) {
13 points[i][ 0 ] = input.nextDouble();
14 points[i][ 1 ] = input.nextDouble();
15 }
16
17
2-D array
read points
// p1 and p2 are the indices in the points' array
18
int p1 = 0 , p2 = 1 ; // Initial two points
track two points
track shortestDistance
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 < points.length; i++) {
24 for ( int j = i + 1 ; j < points.length; 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
for each point i
for each point j
distance between i and j
distance between two points
update shortestDistance
/** 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 }
Enter the number of points: 8
Enter 8 points: -1 3 -1 -1 1 1 2 0.5 2 -1 3 3 4 2 4 -0.5
The closest two points are (1, 1) and (2, 0.5)
The program prompts the user to enter the number of points (lines 6-7). The points are
read from the console and stored in a two-dimensional array named points (lines 12-15).
The program uses the variable shortestDistance (line 19) to store the distance between
the two nearest points, and the indices of these two points in the points array are stored in
p1 and p2 (line 18).
For each point at index i , the program computes the distance between points[i] and
points[j] for all j > i (lines 23-34). Whenever a shorter distance is found, the variable
shortestDistance and p1 and p2 are updated (lines 28-32).
The dist ance between two point s (x1, y1) and (x2, y2) can be computed using the
formula
y 1 ) 2 (lines 43-46).
The program assumes that the plane has at least two points. You can easily modify the
program to handle the case if the plane has zero or one point.
x 1 ) 2
2
( x 2
-
+
( y 2
-
 
 
Search WWH ::




Custom Search