Calculate the overlapping area of two rectangles

Hi!

I have an assignment due to tomorrow at noon and I tried figuring it out myself but I failed. I'd be more than grateful if someone could help me!

You are given a coordinate system. Each rectangle can be defined with 4 numbers with a floating point - its coordinates of its low left angle ( x, y ) , its width and height.
Write a program that reads from the input, defines two rectangles ( based on the numbers of the input ) and gives you an ouput of the are of the their intersecting ( overlapping ) part. If there is no intersection the program should give you an output of 0.

Example :
Input : output
0053
4133 2

0022
-1-111 0

We shouldn't be using arrays and loops in the code. Thank you in advance!
post what you tried? We can't fix it without seeing it.
but basically, you need a third rectangle that is the overlap, then take the area of that which is just a multiply. Solve it on paper. How do you get that third rectangle's coordinates...? Problems like this are 90% math, 10% code... if you know how to get the overlap on paper as a math problem, you can do it with just a few lines of code...
Last edited on
This problem has been asked and answered elsewhere on this forum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;

class Rectangle
{
   double x1, x2, y1, y2;
   void check() { if ( x1 > x2 || y1 > y2 ) { x1 = x2 = y1 = y2 = 0.0; } }
public:
   Rectangle( double xbl = 0.0, double ybl = 0.0, double width = 1.0, double height = 1.0 )
   {
      x1 = xbl;   x2 = x1 + width;   y1 = ybl;   y2 = y1 + height; 
      check();
   }
   double area() { return ( x2 - x1 ) * ( y2 - y1 ); }
   Rectangle operator * ( const Rectangle & other )
   {
      double left   = max( this->x1, other.x1 );
      double right  = min( this->x2, other.x2 );
      double bottom = max( this->y1, other.y1 );
      double top    = min( this->y2, other.y2 );
      return Rectangle( left, bottom, right - left, top - bottom );
   }
   friend istream & operator >> ( istream &in, Rectangle &rectangle )
   {
      double xbl, ybl, width, height;
      in >> xbl >> ybl >> width >> height;
      rectangle = Rectangle( xbl, ybl, width, height );
      return in;
   }
};

int main()
{
   istringstream in( "0 0 5 3\n"
                     "4 1 3 3\n" );
   Rectangle a, b;
   in >> a >> b;
   cout << "Overlap area is " << ( a * b ).area() << '\n';
}

Last edited on
Thanks everyone! Especially thank you againtry!!! You are a life saver.
LOL, I didn't do anything, but there we go :)
Topic archived. No new replies allowed.