2

私はここで自分自身を心から混乱させています...実際に2つの長方形の交点の面積を返すのはどれですか? 説明してください(数学は私を苛立たせます)。任意の助けをいただければ幸いです。

アプローチ 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);

アプローチ 2:

double areaOfIntersection = Math.max(0, Math.max(rect1x2, rect2x2) - Math.min(rect1x1, rect2x1))
                        * Math.max(0, Math.max(rect1y2, rect2y2) - Math.min(rect1y1, rect2y1)); 
4

2 に答える 2

4

あなたのコードはほぼ正しいです。コードを投稿した方法はthis、1 つの四角形をrect2参照し、2 番目の四角形を参照しているように見えるため、混乱しています。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();
于 2013-03-08T17:17:29.787 に答える
1

私がすることは次のとおりです。

長方形をそれぞれ 4 つの点に分割し、それらを並べます。

各長方形の対応する点を比較するだけです。- 左上 - 右上 - 左下 - 右下

交点によって作成された長方形の左上点の x、y 値を計算します。

左隅を探しているので、最初に一番右の点 (最大の x 値) を取得して左上隅の 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

またはもっと簡単に

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 つのコーナーに対してのみこれを行う必要があることに注意してください。

例:左上と右下

編集: ただし、左上が右下より低い場合、それらは交差しません。左上が右下よりも右にあるのと同じ...

于 2013-03-08T17:21:37.627 に答える