Background

This question is a frequently asked question in written tests conducted by Adobe. This question was sent to me by two of my close friends, one of them could easily make it to Adobe and is working with Adobe Noida now.

Problem Definition

In a Plane, If you are given co-ordinates of upper left corner and lower right corner of two rectangles, you need to write a #define macro which returns true/false based on whether triangles intersect/overlap.

Solution:

First let us set up data structure we will use for representation of rectangle so that we can then easily write an algorithm for the given problem. We can declare a structure representing rectangle and it can have x1, y1 and x2, y2 as two points. From a written test perspective it is sufficient to do so. But, It is always better to show your skills in a face to face interview here and be more modular.

First define a structure named Point and then use this structure when you are defining Rectangle. See the definitions below



struct Point
{
int x;
int y;
};

struct Rectangle
{
Point upperLeft;
Point lowerRight;
};



In this figure, consider 5 is the area of rectangle1 we are considering. We need to find conditions in which rectangle2 will not overlap with this.

Conclusions:

  • Any rectangle with it's lower right in areas 1, 2, 3, 4, 7 will not overlap with this rectangle.
  • A rectangle with it's upper left in 3, 6, 7, 8, 9 will not overlap with it.
Conclusion1 can be coded as:

(rectangle2.lowerRight.x < rectangle1.upperLeft.x)
(rectangle2.lowerRight.y > rectangle1.upperLeft.y)

Conclusion2 can be coded as:
  
(rectangle2.upperLeft.x > rectangle1.lowerRight.x)
(rectangle2.upperLeft.y < rectangle1.lowerRight.y)
Hence our final answer is
  
#define intersect(rectangle1, rectangle2) !(conclusion1 conclusion2)

0 comments