2013-03-08 94 views
1

我在此真誠地混淆了自己......哪一個實際返回兩個矩形之間的交集區域?請認真解釋(數學挫敗我)。任何幫助,將不勝感激。獲取兩個相交矩形的面積

方法一: double newX = Math.max(this.x,rect2.x); double newY = Math.max(this.y,rect2.y); return new Rect(newX,newY,Math.min(this.x + this.width,rect2.x + rect2.width) - newX,Math.min(this.y + this.height,rect2.y + rect2 .height) - newY);

方法有兩個:
雙areaOfIntersection = Math.max(0,Math.max(rect1x2,rect2x2) - Math.min(rect1x1,rect2x1)) * Math.max(0,Math.max( rect1y2,rect2y2) - Math.min(rect1y1,rect2y1));

+2

我覺得這個問題在這裏很合適http://math.stackexchange.com/ – 2013-03-08 17:05:37

+0

這是一個數學問題還是一個編程問題? – pamphlet 2013-03-08 17:06:03

回答

4

你的代碼幾乎是正確的。您發佈代碼的方式令人困惑,因爲看起來this引用了一個矩形,而rect2引用了第二個矩形。爲什麼不制定Rect#area()方法而不是分別計算相交面積?

class Rect { 

    double x, y, width, height; 

    ... members and stuff 

    Rect intersection(Rect rect2) { 
     double newX = Math.max(this.x, rect2.x); 
     double newY = Math.max(this.y, rect2.y); 

     double newWidth = Math.min(this.x + this.width, rect2.x + rect2.width) - newX; 
     double newHeight = Math.min(this.y + this.height, rect2.y + rect2.height) - newY; 

     if (newWidth <= 0d || newHeight <= 0d) return null; 

     return new Rect(newX, newY, newWidth, newHeight); 
    } 

    double area() { 
     return this.width * this.height; 
    } 

} 

然後你只想做

Rect intersection = rect1.intersection(rect2);  
double areaOfIntersection = intersection == null ? 0 : intersection.area(); 
+0

這是否處理矩形不相交的情況? – pamphlet 2013-03-08 17:26:42

+0

@AndrewMao其實....我不確定這是否工作...我上面貼的代碼是兩個完全不同的方法.. – BigBug 2013-03-08 17:54:34

+0

固定的情況下,他們根本不相交。 – 2013-03-08 19:07:53

1

繼承人什麼,我會做:

打破矩形進每題4分 - 和命令他們:

你只需要比較每個矩形的修正點。 各自具有: - 左上 - 右上 - 左下 - 右下

到calcuate在x,由交叉點創建的矩形的左上角點的y值:

第一計算通過獲取最右邊的點(最高x值),因爲我們正在尋找的左上角

if rect_1_upper_left_x > rect_2_upper_left_x then 
    intersect_upper_left_x = rect_1_upper_left_x 
else 
    intersect_upper_left_x = rect_2_upper_left_x 
endif 

或者更簡單地說

左上角的x座標
intersect_upper_left_x = max(rect_1_upper_left_x , rect_2_upper_left_x) 

得到左上角的y座標,選擇最低的y值(因爲我們正在尋找的右上角)

intersect_upper_left_y = min(rect_1_upper_left_y , rect_2_upper_left_y) 

請注意,您只需要2對面做到這一點角落;

例如:左上和右下

編輯:雖然,如果你的左上比你更低的右下方,他們不instersect。 相同,如果你的左上方比右下方更靠右...

+0

另外,這隻適用於如果recangles不是在一個角度,但似乎暗示了問題中顯示的代碼 – Allen 2013-03-08 17:41:19