luc*_*ter 2 java algorithm complexity-theory
所以我试着写一个简单的方法,它接受一组四个坐标,并决定它们是否形成一个正方形.我的方法是从一个点开始计算其他三个点和基点之间的距离.从此我们我可以得到具有相同值的两边和一个对角线的两边.然后我用毕达哥拉斯定理来找出边平方是否等于对角线.如果是isSquare方法则返回true,否则我想要的东西.找出是否有一些我可能会错过的情况或者如果方法有问题.谢谢所有的帮助.
public class CoordinatesSquare {
public static boolean isSquare(List<Point> listPoints) {
if (listPoints != null && listPoints.size() == 4) {
int distance1 = distance(listPoints.get(0), listPoints.get(1));
int distance2 = distance(listPoints.get(0), listPoints.get(2));
int distance3 = distance(listPoints.get(0), listPoints.get(3));
if (distance1 == distance2) {
// checking if the sides are equal to the diagonal
if (distance3 == distance1 + distance2) {
return true;
}
} else if (distance1 == distance3) {
// checking if the sides are equal to the diagonal
if (distance2 == distance1 + distance3) {
return true;
}
}
}
return false;
}
private static int distance(Point point, Point point2) {
//(x2-x1)^2+(y2-y1)^2
return (int) (Math.pow(point2.x - point.x, 2) + (Math.pow(point2.y
- point.y, 2)));
}
public static void main(String args[]) {
List<Point> pointz = new ArrayList<Point>();
pointz.add(new Point(2, 2));
pointz.add(new Point(2, 4));
pointz.add(new Point(4, 2));
pointz.add(new Point(4, 4));
System.out.println(CoordinatesSquare.isSquare(pointz));
}
}
//Point Class
public class Point {
Integer x;
Integer y;
boolean isVisited;
public Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if(obj!=null && obj.getClass().equals(this.getClass())){
return ((Point) obj).x.equals(this.x)&&((Point) obj).y.equals(this.y);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
你知道,你可以更容易地做同样的检查.你只需要检查两件事:"四点制作平行四边形"和"其中一个角度是正确的".
首先是真的 P3 = P1 + (P2-P1) + (P4-P1)
而第二次 (P2-P1)*(P4-P1) = 0
A*B点积在哪里?(A.x * B.x + A.y * B.y)
这里唯一的问题是计算错误.你不能指望花车完全相等,所以不是A=B你应该考虑使用像abs(A-B) < E这里E是你的情况下足够小.
| 归档时间: |
|
| 查看次数: |
10361 次 |
| 最近记录: |