-1

Assume that I have 5 rectangle, and each rectangle has 4 parameters, these are x,y,width,height. x and y -> start coordination, w and h ->edges. How we calculate intersection area ?

 int rectangle[5][4];

    int calculate_intersection(){
    ....
    return total;
    }
Sefa Taşcan
  • 57
  • 2
  • 6

1 Answers1

0

You will want to iteratively make new rectangles, each being the intersection of the previous. Let's say you have four rectangles, call them Ri where i is 1, 2, 3, or 4. Let's call the intersection rectangle I4, for the intersection of the 4 rectangles.

First we will want to intersect R1 and R2. Save the resulting width, height, x, and y into I4.

Next we will want to intersect R3 and I4. Save the resulting width, height, x, and y into I4.

Then we will want to intersect R4 and I4. Save the resulting width, height, x, and y into I4.

At this point I4 is the result of intersecting all 4 rectangles, R1, R2, R3, and R4. I'm sure you will now know how to calculate the area given these values.

: : Hints and pseudo code for finding intersection : :

Given the rectangles may be in any orientation and position relative to one another, we'll need to do a little work in figuring out where points lie in respect to each other. Typically, we'll use the MAX and MIN function, or you can use these one-liners:

int max = (a>b) ? a : b;
int min = (a<b) ? a : b;

max here will hold the value of either a or b, whichever is greater, and 'min' will hold the lesser. Now with this we can solve for our points.

To find I4 x-value, we'll need to take the max's of the Ri and Rj rectangles in the x-direction: I4x = max{Ri_x, Rj_x}

To find I4 y-value, we'll need to take the max's of the Ri and Rj rectangles in the y-direction: I4y = max{Ri_y, Rj_y}

To find I4 width-value, we'll need to take the min's of the Ri and Rj rectangles total width, BUT we will need to subtract away the final shifted x location: I4w = min{Ri_x + Ri_w, Rj_x + Rj_w} - I4_x

To find I4 height-value, similarily we'll need to take the min's of the Ri and Rj rectangles total height and subtract away the final shifted y location: I4w = min{Ri_y + Ri_h, Rj_y + Rj_h} - I4_y

dovedevic
  • 673
  • 2
  • 14
  • 33
  • how do to intersect ? It is main problem – Sefa Taşcan Dec 04 '16 at 20:33
  • 1
    @SefaTaşcan: drawn an ASCII diagram of two rectangles that intersect; work out the description of the intersection in terms of the x, y, width, height values of the two rectangles. That's how you do it. If you've not yet learned structures, then have another go at this exercise when you have learned them (next week, or the week after?). You might find that 'bottom left, top right' corners are easier to manipulate than width and height, though the two forms are interchangeable. This assumes that the rectangles are aligned with the axes; if they're at arbitrary angles, you need more info. – Jonathan Leffler Dec 04 '16 at 20:47
  • @SefaTaşcan, Hints/pseudo help? – dovedevic Dec 04 '16 at 20:55