Rectangle Area
It is a simple problem. Given two rectangles, you are asked to return the total area of the region the two rectangles cover. It is abviously that the result equals to the sum of two rectangles' area deduct the area two rectangles both cover.
Some points should be kept an eye on:
- You code must works on every different cases. For example, what if the two rectangle has not insection area? What if one rectangle totally contains the other one?
- You code should be able to work on different kinds of input. The rectangle is given by two points on the cross. You should handle every possible relatively position of these two points. For example, the two point can be top left and bottom right as well as bottom left and top right.
Sample code:
public class RectangleArea {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int t1 = Math.max(B, D);
int b1 = Math.min(B, D);
int l1 = Math.min(A, C);
int r1 = Math.max(A, C);
int t2 = Math.max(F, H);
int b2 = Math.min(F, H);
int l2 = Math.min(E, G);
int r2 = Math.max(E, G);
int area1 = (t1 - b1) * (r1 - l1);
int area2 = (t2 - b2) * (r2 - l2);
int insectArea = 0;
int t3 = Math.min(t1, t2);
int b3 = Math.max(b1, b2);
int l3 = Math.max(l1, l2);
int r3 = Math.min(r1, r2);
if (t3 > b3 && r3 > l3) {
insectArea = (t3 - b3) * (r3 - l3);
}
return area1 + area2 - insectArea;
}
}