2016-12-28 218 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