javaarraysdistanceclosest-points

How can I write a function to find 2 closest points in 2D dimensional array in Java?


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

Solution

  • 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};
    }