2016-12-28 130 views
2

此问题已多次询问,我看到很多线索,但我的查询非常具体。如何查看两个矩形是否重叠。在我的代码中发现错误的测试用例是:检查两个矩形是否重叠

l2 = new RectanglePoint(0,7);
r2 = new RectanglePoint(6,10);
l1 = new RectanglePoint(0,7);
r1 = new RectanglePoint(6,0);
函数调用:isOverlap(new Rectangle(l1,r1),new Rectangle(l2,r2));

我的代码:

class RectanglePoint { 
    int x; 
    int y; 

    public RectanglePoint(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

class Rectangle { 
    RectanglePoint topLeft; 
    RectanglePoint bottomRight; 

    public Rectangle(RectanglePoint topLeft, RectanglePoint bottomRight) { 
     this.topLeft = topLeft; 
     this.bottomRight = bottomRight; 
    } 
} 

public class RectangleOverlap { 
    public boolean isOverlap(Rectangle rect1, Rectangle rect2) { 
     return isOverlapHelper1(rect1.topLeft, rect1.bottomRight, rect2.topLeft, 
       rect2.bottomRight); 
    } 


    private boolean isOverlapHelper1(RectanglePoint topLeftA, 
      RectanglePoint bottomRightA, RectanglePoint topLeftB, 
      RectanglePoint bottomRightB) { 
     if (topLeftA.y < bottomRightB.y || topLeftB.y < bottomRightA.y) { 
      return false; 
     } 
     if (topLeftA.x > bottomRightB.x || topLeftB.x > bottomRightA.x) { 
      return false; 
     } 
     return true; 
    } 

bug是在条件:如果(topLeftA.y < bottomRightB.y || topLeftB.y < bottomRightA.y)

请帮忙。我已经在这里花了很多时间。

+0

你是什么意思的更大“的错误是在条件...”?你期望的结果是什么,你得到了什么?请参见[如何创建最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 –

+0

根据条件:两个矩形不会重叠,但如果我用纸笔绘制两个矩形,则它重叠 – ojas

回答

2

你的条件if (topLeftA.y < bottomRightB.y || topLeftB.y < bottomRightA.y)(topLeftA.x > bottomRightB.x || topLeftB.x > bottomRightA.x)假设属性topLeft真的是矩形的左上角顶点和bottomRight真的是矩形的右下角顶点。但是,您的初始化代码this.topLeft = topLeft;this.bottomRight = bottomRight;实际上并不能保证这一点。如果初始化对矩形使用了错误的顶点,那么您的代码不会纠正该问题,并且以后的方法可能会出错。

这就是你的测试用例中发生的情况。你不清楚你的坐标是笛卡尔坐标(增加的y值上升)还是图形的(增加的y值下降)。但是在任何一种情况下,你的两个测试矩形之一的定义都很差。您的第一个矩形从(0,7)到(6,0),这在笛卡尔坐标中是正确的,但在图形坐标中是错误的。您的第二个矩形从(0,7)到(6,10),这在图形坐标中是正确的,但在笛卡尔坐标中是错误的。无论您使用哪个坐标,其中一个矩形都是错误的,因此您的重叠代码失败。

给定您的名字,您应该在创建矩形时更正坐标或返回错误坐标的错误。为了校正笛卡尔坐标,让topLeft的x坐标是两个给定顶点的x坐标的最小值,topLeft的y坐标是两个给定顶点的y坐标的最大值, bottomRight的坐标是两个给定顶点的x坐标的最大值,bottomRight的y坐标是两个给定顶点的y坐标的最小值。然后调用者可以使用该矩形的任意两个相对的顶点并仍然获得有效的结果。

0

你假设输入l1l2是要去总是topLeft坐标和r1r2是要始终bottomRight坐标。 要坚持这样的假设,我建议你使用一些kindda条件/验证,以确保输入与你的假设一致,

使用此代码里面isOverlap()之前调用的上述isOverlapHelper1()

if ((rect1.topLeft.x > rect1.bottomRight.x) || 
(rect1.topLeft.y < rect1.bottomRight.y) || 
(rect2.topLeft.x > rect2.bottomRight.x) || 
(rect2.topLeft.y < rect2.bottomRight.y)) 
    throw new IllegalArgumentException("Wrong co-ordinates"); 

简化前条件:

  1. X坐标左上的应小于该BottomRight的
  2. TOPL的
  3. Y坐标EFT应该比BottomRight


或者你可以在构造Rectangle()

对于比较简单和语言无关的解释检查这一点,结账my answer on a similar thread

相关问题