Skip to content

Instantly share code, notes, and snippets.

@prameshbhattarai
Created October 9, 2019 11:55
Show Gist options
  • Save prameshbhattarai/ebad8dce75cfda2a7846690997e02cf2 to your computer and use it in GitHub Desktop.
Save prameshbhattarai/ebad8dce75cfda2a7846690997e02cf2 to your computer and use it in GitHub Desktop.
Area of two intersected rectangle.
public class AreaOfRectangle {
public static long area(int length, int breadth) {
return Math.abs(length * breadth);
}
public static boolean isOverlapped(int K, int L, int M, int N,
int X, int Y) {
return K < X && X < M && L < Y && Y < N;
}
public static long solution(int K, int L, int M, int N,
int P, int Q, int R, int S) {
long area1 = area(M - K, N - L);
long area2 = area(R - P, S - Q);
System.out.println(area1 + " " + area2);
long overlappedArea = 0;
if (isOverlapped(K, L, M, N, P, S)) overlappedArea = area(P - M, S - L);
if (isOverlapped(K, L, M, N, P, Q)) overlappedArea = area(P - M, Q - N);
if (isOverlapped(K, L, M, N, R, S)) overlappedArea = area(R - K, S - L);
if (isOverlapped(K, L, M, N, R, Q)) overlappedArea = area(R - K, L - N);
System.out.println(overlappedArea);
long finalArea = area1 + area2 - overlappedArea;
System.out.println(finalArea);
if(finalArea > 2_147_483_647L) {
return -1;
}
return finalArea;
}
public static void main(String... args) {
long area = solution(-4, 1, 2, 6,
0, -1, 4, 3);
System.out.println("-----------");
System.out.println(area);
System.out.println("-----------");
area = solution(0, 0, 1, 1,
3, 1, 4, 3);
System.out.println("-----------");
System.out.println(area);
System.out.println("-----------");
area = solution(-40000, 10000, 20000, 60000,
0, -10000, 40000, 30000);
System.out.println("-----------");
System.out.println(area);
System.out.println("-----------");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment