【算法设计与分析基础】7、蛮力求平面中距离最近的两点

/**
	 * 蛮力求平面中距离最近的两点
	 * @param points 所有点的坐标点
	 * @return
	 */
	public static DataBean bruteForceClosestPoint(List<Pair> points)
	{
		Double minDistance = Double.MAX_VALUE;
		//遍历数据,获取x,y
		//获取map的迭代器
		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);
				//求两点距离
				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;
		}
	}

  

 

辅助类:

 

package cn.xf.algorithm.ch03.bean;

public class DataBean {
	/**
	 * 平面坐标的x坐标
	 */
	private Long x1;
	/**
	 * 同上
	 */
	private Long y1;
	
	private Long x2;
	
	private Long y2;
	/**
	 * 两点之间的距离
	 */
	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;
	}
}

  

测试:

public static void main(String[] args) {
//		List data = Arrays.asList(12,32,44,12,55,34,77,234,3567,97);
//		List data = new ArrayList<Integer>();
//		data.addAll(Arrays.asList(12,32,44,12,55,34,77,234,3567,97));
//		int k = 234;
//		
//		System.out.println(Found.sequentialSearch2(data, k));
		
		//创建对应的map集合
		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());
		
	}

  

结果:

 

posted @ 2017-03-16 10:16  cutter_point  阅读(349)  评论(0编辑  收藏  举报