Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

total area of intersecting rectangles

Tags:

algorithm

I need an algorithm to solve this problem: Given 2 rectangles intersecting or overlapping together in any corner, how do I determine the total area for the two rectangles without the overlapped (intersection) area? Meaning the area of intersection has to be calculated once, either with the first rectangle, or with second one.

like image 727
al_khater Avatar asked Dec 28 '10 21:12

al_khater


People also ask

What is the area of overlap?

The OverlapArea function is a Spatial Numeric measurement that calculates the total area (or length or count) of overlap between features in the current layer and features in the target layer.


2 Answers

That's easy. First compute coordinates of intersection, which is also a rectangle.

left = max(r1.left, r2.left) right = min(r1.right, r2.right) bottom = max(r1.bottom, r2.bottom) top = min(r1.top, r2.top) 

Then, if intersection is not empty (left < right && bottom < top), subtract it from the common area of two rectangles: r1.area + r2.area - intersection.area.

PS:

  1. Assumption 1: rectangles are aligned by the coordinate axes, that's usually the case.
  2. Assumption 2: y axis here increases upwards, for example, in a graphics application, the y axis increases downwards, you may need to use:

bottom = min(r1.bottom, r2.bottom) top = max(r1.top, r2.top)

like image 55
Nikita Rybak Avatar answered Oct 02 '22 08:10

Nikita Rybak


Here is complete solution for this algorithm using Java:

public static int solution(int K, int L, int M, int N, int P, int Q, int R,         int S) {     int left = Math.max(K, P);     int right = Math.min(M, R);     int bottom = Math.max(L, Q);     int top = Math.min(N, S);      if (left < right && bottom < top) {         int interSection = (right - left) * (top - bottom);         int unionArea = ((M - K) * (N - L)) + ((R - P) * (S - Q))                 - interSection;         return unionArea;     }     return 0; }  
like image 31
Vikasdeep Singh Avatar answered Oct 02 '22 09:10

Vikasdeep Singh