JAVA Listing 7.3 gives a program that finds two points in a two-dimensional spac
ID: 3693575 • Letter: J
Question
JAVA
Listing 7.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: doublet[][] 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 squareroot (x_2 - x_1)^2 + (y_2 - y_1)^2 + (z_2 - z_1)^2.Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
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}};
int size = points.length;
double min_distance = 1000,d;
int i_index = 0,j_index=0;
for(int i = 0;i<size-1;i++)
for(int j=i+1;j<size;j++){
d = Math.sqrt(Math.pow((points[j][0]-points[i][0]),2) + Math.pow((points[j][1]-points[i][1]),2) + Math.pow((points[j][2]-points[i][2]),2));
if(d < min_distance){
min_distance = d;
i_index = i;
j_index = j;
}
}
System.out.println("The new closest points are : ");
System.out.printf("%.1f , %.1f , %.1f ",points[i_index][0],points[i_index][1],points[i_index][2]);
System.out.printf("%.1f , %.1f , %.1f",points[j_index][0],points[j_index][1],points[j_index][2]);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.