0

How can I find 2 closest points in an Array in Java?

My input is,

int[][] tour = {{0, 0}, {4, 0}, {4, 3}, {0, 3}};

static double calcDistanceBetweenWaypoints(int[] src, int[] dest) {
        assert src.length == 2;
        assert dest.length == 2;
        //(0,0),(0,4)
        return Math.sqrt((dest[0] - src[0])*(dest[0] - src[0]) + (dest[1] - src[1])*(dest[1] - src[1]));
    }

   public static int[][] getClosestWaypoints(int[][] tour) {
       throw new UnsupportedOperationException("Not supported yet.");
       //I dont know how to do with this function.
   }

my output is,

closest waypoints    : [(4/0) -> (4/3)], distance: 3,00
INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
  • 1
    Cycle through the points, compare with the others keeping track of the distance between the first two, and keeping track of the points values themselves. When cycling, if the distance is less then the previous saved one, save the new one and the new points. At the end you'll have the closest couple. (This is the quick and dirty solution. There are probably more efficient solutions.) – Federico klez Culloca May 17 '19 at 12:36
  • Possible duplicate of [Finding the closest points in an array](https://stackoverflow.com/questions/50884358/finding-the-closest-points-in-an-array) – Ng Sharma May 17 '19 at 12:39
  • more info https://www.geeksforgeeks.org/closest-pair-of-points-using-divide-and-conquer-algorithm/ – Ng Sharma May 17 '19 at 12:40
  • In short [`Math.hypot`](https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#hypot(double,double)) shortens the expression to `Math.hypot(dest[0] - src[0], dest[1] - src[1])` or you could use the square of the distance, without `sqrt`. – Joop Eggen May 17 '19 at 13:02
  • What about [(0/0) -> (0/3)]? – Maurice Perry May 17 '19 at 13:16

1 Answers1

0

Another solution:

public static int[][] getClosestWaypoints(int[][] tour) {
    double minDist = Integer.MAX_VALUE;
    int[] pt1 = null;
    int[] pt2 = null;
    for (int i = 0; i < tour.length-1; ++i) {
        for (int j = i+1; j < tour.length; ++j) {
            double dist = calcDistanceBetweenWaypoints(tour[i], tour[j]);
            if (dist < minDist) {
                minDist = dist;
                pt1 = tour[i];
                pt2 = tour[j];
            }
        }
    }
    return new int[][] {pt1, pt2};
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24