Thursday, 19 September 2013

Java Arrays: Find Two Points In A Three-Dimensional Space Nearest To Each Other

Java Arrays: Find Two Points In A Three-Dimensional Space Nearest To Each
Other

As the title suggests, I'm working on a homework assignment where we are
limited to using multi-dimensional arrays in order to create a program
that finds two points nearest to each other in a three dimensional space.
So far my code looks like this (hybridized from examples in my textbook
and my own code):
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1, p3 = 2;
double shortestDistance = distance(points[p1][0] , points[p1][1] ,
points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2] ,
points[p3][0] , points[p3][1] , points[p3][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , [points[j][0] ,
points[j][1] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0]
+ "," + points[p1][1] +
and (" + points[p2][0] + "," );
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) +
((z2 - z1) * (z2 - z1)));
}
}
Thanks for the help guys. I'm running on 2 hours of sleep for 2 days now
so please excuse any stupid questions or sloppy code.

No comments:

Post a Comment