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.
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.
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:
bottom = min(r1.bottom, r2.bottom) top = max(r1.top, r2.top)
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With