Challenge Description:
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
You will be given the x/y co-ordinates of several locations.
You will be laying out 1 cable between two of these locations.
In order to minimise the cost, your task is to find the shortest distance
between a pair of locations, so that pair can be chosen for the cable installation.
Your program should accept as its first argument a path to a filename.
The input file contains several sets of input. Each set of input starts
with an integer N (0<=N<=10000), which denotes the number of points in this set.
The next N line contains the coordinates of N two-dimensional points.
The first of the two numbers denotes the X-coordinate and the
latter denotes the Y-coordinate. The input is terminated by a set whose N=0.
This set should not be processed.
The value of the coordinates will be less than 40000 and non-negative. eg.
Input sample:
5
0 2
6 67
43 71
39 107
189 140
Output sample:
For each set of input produce a single line of output containing a floating
point number (with four digits after the decimal point) which denotes the distance
between the closest two points. If there is no such two points in the input
whose distance is less than 10000, print the line INFINITY. eg.
36.2215
package codejam_class;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.Scanner;/** * * @author RAYMARTHINKPAD */public class ClosestPairMethods { private final DecimalFormat twoDForm = new DecimalFormat("#.####"); private ArrayList finalArl; public void storeUserInput(int numP) { Scanner scan = new Scanner(System.in); ArrayList<Integer> arl = new ArrayList<>(); for (int i = 0; i < numP; i++) { int j = i + 1; System.out.print("Enter x" + j + ": "); int x = scan.nextInt(); System.out.print("Enter y" + j + ": "); int y = scan.nextInt(); arl.add(x); arl.add(y); } this.storeArrayList(arl); System.out.println(this.returnMinVal(this.finalArl)); } public void storeArrayList(ArrayList<Integer> al) { ArrayList list = new ArrayList(); double res; for (int i = 0; i < (al.size() - 3); i += 2) { int x1 = al.get(i); int x2 = al.get(i + 2); int y1 = al.get(i + 1); int y2 = al.get(i + 3); res = this.computeD(x1, x2, y1, y2); list.add(twoDForm.format(res)); } this.finalArl = list; } public double computeD(int x1, int x2, int y1, int y2) { return Math.sqrt((Math.pow((Math.abs(x2 - x1)), 2)) + (Math.pow((Math.abs(y2 - y1)), 2))); } public double returnMinVal(ArrayList arl) { Object minObj = arl.get(0); String minS = String.valueOf(minObj); double minDouble = 0.0; for(int i = 0; i < arl.size()-1; i++) { Object next = arl.get(i); String nextS = String.valueOf(next); double nextDouble = Double.parseDouble(nextS); minDouble = Double.parseDouble(minS); if(nextDouble<minDouble) { minDouble = nextDouble; } } return minDouble; }}