-1

I am having problems figuring out this part of the program:

Write a non-member function, intersection() that takes two Rectangle parameters and returns a Rectangle containing the intersection of the two. Of course, if the two Rectangles don't intersect, it should return the default Rectangle.

So far this is my .cpp code:

Rectangle::Rectangle()
{
    p1.x = 0;
    p1.y = 0;
    p2.x = 0;
    p2.y = 0;
}
Rectangle::Rectangle(double x, double y, double width, double height)
{
    p1.x = x;
    p1.y = y;
    p2.x = x + width;
    p2.y = y + height;
}
double Rectangle::getArea() const
{
    return (p2.x - p1.x) * (p2.y - p1.y);
}
double Rectangle::getWidth() const
{
    return (p2.x - p1.x);
}
double Rectangle::getHeight() const
{
    return (p2.y - p1.y);
}
double Rectangle::getX() const
{
    return p1.x;
}
double Rectangle::getY() const
{
    return p1.y;
}
void Rectangle::setLocation(double x, double y)
{
    p1.x = x;
    p1.y = y;
}
void Rectangle::setSize(double width, double height)
{
    p2.x = width;
    p2.y = height;
}

Rectangle intersection(const Rectangle& rec1, const Rectangle& rec2)
{
    double ix = 0.0;
    double iy = 0.0;
    double iwidth = 0.0;
    double iheight = 0.0;

    if(rec1.getX() > rec2.getX() && rec2.getX() > (rec1.getX() + rec1.getWidth()) 
        && rec1.getY() > rec2.getY() && rec2.getY() > (rec1.getY() + rec1.getHeight()))
    {
        ix = rec2.getX();
        iy = rec2.getY();
        iwidth = rec1.getX() + rec1.getWidth();
        iheight = rec1.getY() + rec1.getHeight();
    }

I didn't write the "else" part because first, this "if statement should check correct for some cases, but doesn't; I am assuming that (0, 0) is in the bottom left corner, because I already try it with (0, 0) being in the top left corner and does not work

digital_revenant
  • 3,274
  • 1
  • 15
  • 24
user2904220
  • 7
  • 1
  • 2
  • Your `setSize` function is incorrect. Unknown if this influences your result because you did not include test code. – Jongware Oct 21 '13 at 17:54

1 Answers1

3

Consider intersection of rectangles as intersection of 2 pairs of intervals:

First pair is intersection of horizontal sides of rectangles:

Intersection1 = (rec1.getX(), rec1.getX()+rec1.getWidth())&(rec2.getX(), rec2.getX()+rec2.getWidth())

Second pair is intersection of vertical sides of rectangles:

Intersection2 = (rec1.getY(), rec1.getY()+rec1.getHeight())&(rec2.getY(), rec2.getY()+rec2.getHeight())

If both of these intersections are not empty - then you can make a result intersection rectangle which sides are these intersections.

All you need to do is to properly implement interval intersection function.

Sergey
  • 406
  • 2
  • 6