I have a love and hate relationship with this question, attempted in 2nd edition and didn't quite get my algorithm to work for all cases, however after another attempt on this latest edition - this is a solution that works every time and will provide a zero result for no overlap.

How does it work? Essentially for each axis it looks for an overlap between the 2 rectangles, once it has found commonality (i == n), it sets the origin and starts counting the height (or width). It could easily be extended to 3 or more rectangles - just keep nesting the 'for' loops.

-(Rectangle *) intersect: (Rectangle *) r2

{

int x1 = self.origin.x;

int y1 = self.origin.y;

int h1 = self.height;

int w1 = self.width;

int x2 = r2.origin.x;

int y2 = r2.origin.y;

int h2 = r2.height;

int w2 = r2.width;

int x3 = 0, y3 = 0, h3 = 0, w3 = 0;

BOOL boolY = true, boolX = true;

// finding y axis data

for (int i = y1; i < (y1 + h1); i++)

{

for (int n = y2; n < (y2 + h2); n++)

{

if (i == n)

{

h3++;

if (boolY) {

y3 = i;

boolY = false;

}

}

}

}

NSLog(@"h3 is %i", h3);

NSLog(@"y3 is %i", y3);

// finding x axis data

for (int i = x1; i < (x1 + w1); i++)

{

for (int n = x2; n < (x2 + w2); n++)

{

if (i == n)

{

w3++;

if (boolX) {

x3 = i;

boolX = false;

}

}

}

}

NSLog(@"w3 is %i", w3);

NSLog(@"x3 is %i", x3);

Rectangle *returnRect = [[Rectangle alloc]init];

XYPoint *returnPoint = [[XYPoint alloc] init];

[returnPoint setX:x3 andY:y3];

returnRect.origin = returnPoint;

[returnRect setWidth:w3 andHeight:h3];

return returnRect;

}