Tuesday, December 18, 2012

Question 1


Given co-ordinates (x1,y1),(x2,y2) and (x3,y3),(x4,4). Check if two rectangles overlap.

0 if they overlap
1 if they do not overlap

hint: no need to use distance formulae

2 comments:

  1. if (((x3 >= x1 && x3 <= x2 ||
    x3 <= x1 && x3 >= x2) &&
    (y3 >= y1 && y3 <= y2) ||
    y3 <= y1 && y3 >= y2)) ||
    ((x4 >= x1 && x4 <= x2 ||
    x4 <= x1 && x4 >= x2) &&
    (y4 >= y1 && y4 <= y2) ||
    y4 <= y1 && y4 >= y2))) {
    result = 0;
    } else {
    result = 1;
    }

    ReplyDelete
  2. Hope this covers all corner cases too
    #include
    typedef struct rect{
    float x1;
    float y1;
    float x2;
    float y2;
    }rect;

    int overlap(rect rect1,rect rect2){
    if(rect1.x2-rect1.x1<rect2.x1-rect1.x1){
    return 0;
    }
    if(rect2.x2-rect2.x1<rect1.x1-rect2.x1){
    return 0;
    }
    if(rect1.y2-rect1.y1<rect2.y1-rect1.y1){
    return 0;
    }
    if(rect1.y2-rect1.y1<rect2.y1-rect1.y1){
    return 0;
    }
    return 1;
    }

    int main(){

    rect rect1;
    rect rect2;

    rect1.x1=3;
    rect1.y1=3;
    rect1.x2=6;
    rect1.y2=6;

    rect2.x1=4;
    rect2.y1=4;
    rect2.x2=8;
    rect2.y2=8;
    printf("%d",overlap(rect1,rect2));

    }

    ReplyDelete