import java.util.*; import java.lang.*; import java.io.*; class My2dPoint { double x; double y; public My2dPoint(double x1, double y1) { x=x1; y=y1; } } class CompareByX implements Comparator { public int compare(My2dPoint p1, My2dPoint p2) { if (p1.x < p2.x) return -1; if (p1.x == p2.x) return 0; return 1; } } /* An object of the above comparator class is used by java.util.Arrays.sort() in main to sort an array of points by x-coordinates */ class Auxiliaries { public static double distSquared(My2dPoint p1, My2dPoint p2) { double result; result = (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y); return result; } } public class HW4 { public static void main (String argv []) throws IOException { int range = 1000000; // Range of x and y coordinates in points System.out.println("Enter the number of points"); InputStreamReader reader1 = new InputStreamReader(System.in); BufferedReader buffer1 = new BufferedReader(reader1); String npoints = buffer1.readLine(); int numpoints = Integer.parseInt(npoints); // numpoints is now the number of points we wish to generate My2dPoint inputpoints [] = new My2dPoint [numpoints]; // array to hold points int px, py; double dx, dy, dist; int i,j; double currbest; My2dPoint currfirst, currsecond; long tStart, tEnd; for (i = 0; i < numpoints; i++) { px = (int) ( range * Math.random()); dx = (double) px; py = (int) (range * Math.random()); dy = (double) py; inputpoints[i] = new My2dPoint(dx, dy); } // array inputpoints has now been filled tStart = System.currentTimeMillis(); currfirst = inputpoints[0]; currsecond = inputpoints[1]; currbest = Auxiliaries.distSquared(currfirst, currsecond); for (i = 0; i < numpoints - 1; i++) { for (j = i+1; j < numpoints; j++) { dist = Auxiliaries.distSquared(inputpoints[i],inputpoints[j]); if (dist < currbest) { currfirst = inputpoints[i]; currsecond = inputpoints[j]; currbest = dist; } } } tEnd = System.currentTimeMillis(); System.out.println("Point 1: " + currfirst.x + " , " + currfirst.y); System.out.println("Point 2: " + currsecond.x + " , " + currsecond.y); System.out.println("Distance Squared: " + currbest); System.out.println("Time taken in Milliseconds: " + (tEnd - tStart)); /* The following is just to remind you of how to use a library Sort */ CompareByX c = new CompareByX(); java.util.Arrays.sort(inputpoints,c); } }