[Basis of algorithm design and analysis] 7. The two closest points in the plane and two points in algorithm design and analysis
/*** The coordinates of the closest two points in the plane * @ param points all points * @ return */public static DataBean bruteForceClosestPoint (List <Pair> points) {Double minDistance = Double. MAX_VALUE; // traverses data and obtains x, y // gets the map iterator DataBean dbOld = new DataBean (); dbOld. setPointDistance (minDistance); for (int I = 0; I <points. size (); ++ I) {Pair point1 = points. get (I); for (int j = I + 1; j <points. size (); ++ j) {Pair point2 = points. get (j); // calculate the two-point distance from DataBean db = new DataBean (); db. setX1 (point1.x); db. setY1 (point1.y); db. setX2 (point2.x); db. setY2 (point2.y); db. setPointDistance (Found. getDistance (point1.x, point1.y, point2.x, point2.y); dbOld = Found. getMinDouble (db, dbOld) ;}return dbOld;} public static Double getDistance (Long x1, Long y1, Long x2, Long y2) {Double distance = Math. sqrt (Math. pow (x1-x2), 2) + Math. pow (y1-y2), 2); return distance;} public static DataBean getMinDouble (DataBean d1, DataBean d2) {if (d1 = null | d2 = null) return null; if (d1.getPointDistance () <d2.getPointDistance () {return d1;} else {return d2 ;}}
Auxiliary class:
Package cn. xf. algorithm. ch03.bean; public class DataBean {/*** x coordinate of plane coordinates */private Long x1;/*** same as above */private Long y1; private Long x2; private Long y2; /*** distance between two points */private Double pointDistance; public Double getPointDistance () {return pointDistance;} public void setPointDistance (Double pointDistance) {this. pointDistance = pointDistance;} public Long getX1 () {return x1;} public void setX1 (Long x1) {this. x1 = x1;} public Long getY1 () {return y1;} public void setY1 (Long y1) {this. y1 = y1;} public Long getX2 () {return x2;} public void setX2 (Long x2) {this. x2 = x2;} public Long getY2 () {return y2;} public void setY2 (Long y2) {this. y2 = y2 ;}}
package cn.xf.algorithm.ch03.bean;public class Pair {public Long x;public Long y;public Pair(Long x, Long y) {this.x = x;this.y = y;}}
Test:
Public static void main (String [] args) {// List data = Arrays. asList (77,234,356,); // List data = new ArrayList <Integer> (); // data. addAll (Arrays. asList (77,234,356, 234,); // int k =; // System. out. println (Found. sequentialSearch2 (data, k); // create a map set List <Pair> points = new ArrayList <Pair> (); points. add (new Pair (1l, 1l); points. add (new Pair (2l, 2l); points. add (new Pair (3l, 4l); points. add (new Pair (16l, 13l); points. add (new Pair (4l, 12l); points. add (new Pair (5l, 1l); DataBean result = Found. bruteForceClosestPoint (points); System. out. println ("X1 =" + result. getX1 () + ": Y1 =" + result. getY1 (); System. out. println ("X2 =" + result. getX2 () + ": Y2 =" + result. getY2 (); System. out. println (result. getPointDistance ());}
Result: