Interview Questions

How will you detect if two rectangles intersect ......

Microsoft Interview Questions and Answers


(Continued from previous question...)

134. How will you detect if two rectangles intersect ......

Question:
How will you detect if two rectangles intersect and find their intersection. Write test cases for same.


maybe an answer:


public boolean intersects(Rectangle r, Rectangle r1) {
int tw = r1.width;
int th = r1.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = r1.x;
int ty = r1.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}

(Continued on next question...)

Other Interview Questions