Skip to content

Instantly share code, notes, and snippets.

@kwangshin
Created September 17, 2015 14:41
Show Gist options
  • Save kwangshin/cbc5ca6eb3705cb5d9cf to your computer and use it in GitHub Desktop.
Save kwangshin/cbc5ca6eb3705cb5d9cf to your computer and use it in GitHub Desktop.
Get the sum of area of two rectangles.
/**
* Created by Kwangshin on 2015-09-17.
* Email : kwangshin@gmail.com
*/
public class TwoRectanglesArea {
public int getAreaOfTwoRectangles(int K, int L, int M, int N, int P, int Q, int R, int S) {
// Get the sum of area of two rectangles separately, i.e., no concern about the overlapped area.
long twoRectanglesAreaSeparately = this.getTwoRectanglesAreaSeparately(K, L, M, N, P, Q, R, S);
// Overlapping area right is the smaller value in two rectangles right values.
int overlappingAreaRight = (R < M) ? R : M;
// Overlapping area left is the bigger value in two rectangles left values.
int overlappingAreaLeft = (K < P) ? P : K;
// Get overlapping area width...
int overlappingAreaWidth = overlappingAreaRight - overlappingAreaLeft;
if(overlappingAreaWidth <= 0) {
// Two rectangles are not overlapped.
return twoRectanglesAreaSeparately > 2147483647 ? -1 : (int) twoRectanglesAreaSeparately;
}
// Overlapping area top is the smaller value in two rectangles top values.
int overlappingAreaTop = (N < S) ? N : S;
// Overlapping area bottom is the bigger value in two rectangles bottom values.
int overlappingAreaBottom = (L < Q) ? Q : L;
// Get overlapping area height...
int overlappingAreaHeight = overlappingAreaTop - overlappingAreaBottom;
if(overlappingAreaHeight <= 0) {
// Two rectangles are not overlapped.
return twoRectanglesAreaSeparately > 2147483647 ? -1 : (int) twoRectanglesAreaSeparately;
}
// Two rectangles have the overlapped area.
long overlappedRectangleArea = overlappingAreaWidth * overlappingAreaHeight;
long areaOfSumOfRectangles = twoRectanglesAreaSeparately - overlappedRectangleArea;
return areaOfSumOfRectangles > 2147483647 ? -1 : (int) areaOfSumOfRectangles;
}
private long getTwoRectanglesAreaSeparately(int K, int L, int M, int N, int P, int Q, int R, int S) {
// The area of first rectangle.
int firstRectangleWidth = M-K;
int firstRectangleHeight = N-L;
long firstRectangleArea = firstRectangleWidth * firstRectangleHeight;
// The area of second rectangle.
int secondRectangleWidth = R-P;
int secondRectangleHeight = S-Q;
long secondRectangleArea = secondRectangleWidth * secondRectangleHeight;
long sumOfTwoRectanglesSeparately = firstRectangleArea + secondRectangleArea;
return sumOfTwoRectanglesSeparately;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment