Amazon Interview Question
Applications DevelopersCountry: United States
Interview Type: Written Test
Good approach, I think the following correction is needed:
d.topy = max(ra.topy, rb.topy);
d.boty = min(ra.boty, rb.boty);
int doesRectOverlap(rect ra, rect rb){
if ((rb.topy < ra.boty) || (ra.topy < rb.boty) || (rb.topx > ra.botx) || (ra.topx > rb.botx))
return 0; do not overlap
return 1; // do overlap.
}
int doesRectOverlap(rect ra, rect rb){
if ((rb.topy < ra.boty) || (ra.topy < rb.boty) || (rb.topx < ra.botx) || (ra.topx < rb.botx))
return 0; do not overlap
return 1; // do overlap.
}
you are both wrong, you want to consider both horizonal and vertical;
bool doesRectOverlap(rect ra, rect rb)
{
bool ret=0;
ret|=(ra.topx<rb.topx)&&(ra.botx>rb.topx)&&(ra.topy<rb.topy)&&(ra.boty>rb.topy);
ret|=(ra.topx<rb.topx)&&(ra.botx>rb.topx)&&(ra.topy<rb.boty)&&(ra.boty>rb.boty);
ret|=(ra.topx<rb.botx)&&(ra.botx>rb.botx)&&(ra.topy<rb.topy)&&(ra.boty>rb.topy);
ret|=(ra.topx<rb.botx)&&(ra.botx>rb.botx)&&(ra.topy<rb.boty)&&(ra.boty>rb.boty);
return ret;
}
int doesrect(struct rect ra,struct rect rb)
{
struct rect temp;
temp.topx = (ra.topx<rb.topx)?ra.topx:rb.topx;
temp.topy = (ra.topy<rb.topy)?rb.topy:ra.topy;
temp.botx = (ra.botx<rb.botx)?rb.botx:ra.botx;
temp.boty = (ra.boty<rb.boty)?ra.boty:rb.boty;
if(((temp.botx-temp.topx)>(ra.botx-ra.topx + rb.botx-rb.topx)) || ((temp.topy-temp.boty)>(ra.topy-ra.boty + rb.topy-rb.boty)))
return 0;
return 1;
}
Do it this way .. Make a rectangle d covering both the rectangles.. the length and width of this new rectangle has to be less than the sum of both the rectangles for any overlap
- kkr.ashish January 21, 2014