0
votes
//C# Console Application Home assignment

I have 8 coordinates like this:

(x1, y1) (x2, y2) ... (x8, y8) //The first 4 coordinates are for 1st rectangle //The rest for 2nd rectangle

I store the values like this:

int[,] array2D = new int[8,2];
array2d[0,0] = x1;
array2d[0,1] = y1;
array2d[1,0] = x2;
array2d[1,1] = y2;
//...
array[7,0] = x8;
array[7,1] = y8;

I want to calculate area of intersection between those coordinates.

I already have this code to check when the rectangles aren't overlapping (it works):

if (!(array2D[2, 1] <= array2D[4, 1] && array2D[0, 1] >= array2D[6, 1]
                && array2D[2, 0] >= array2D[4, 0] && array2D[0, 0] <= array2D[6, 0]))
            {
//not overlapping
}
{
//overlapping
}

I need help with algorithm to get the area of intersection.

NOTE: Coordinates can have negative values.

2
Do you need algorithm or you are looking for function in one of the Dot Net libraries? - Rami Yampolsky
Algorithm or function, so i can understand and can complete my code. - M. Coutinho

2 Answers

1
votes

I would use the Rectangle.Intersect method from System.Drawing. There's no point in reinventing the wheel... ;-)

Returns a third Rectangle structure that represents the intersection of two other Rectangle structures. If there is no intersection, an empty Rectangle is returned.

0
votes

The simplest solution is to first note that intersection of rectangles (or indeed anything) is commutative. That is, if I want to intersect A, B and C, I can intersect A and B and then intersect that with C OR intersect B and C and then intersect the result with A.

Therefore, store a rectangle and intersect it with successive rectangles. So you start with the first rectangle, intersect that with the second. Then you intersect the result with the third and so on.

This will give you the intersection rectangle, so you can simply compute the area.

Update

Your problem seems to mainly be your format for your rectangles. Namely, the 4 vertices defining the rectangle. This can easily be turned in to an X/Y for the top left and a width and height by taking the top left to be your first vertex (obviously), the width and height are the difference between this vertex and the bottom right