r/dailyprogrammer • • Aug 11 '12

[8/10/2012] Challenge #87 [easy] (Rectangle intersection)

Write a function that calculates the [intersection](http://en.wikipedia.org/wiki/Intersection_(set_theory)) of two rectangles, returning either a new rectangle or some kind of null value.

You're free to represent these rectangles in any way you want: tuples of numbers, class objects, new datatypes, anything goes. For this challenge, you'll probably want to represent your rectangles as the x and y values of the top-left and bottom-right points. (Rect(3, 3, 10, 10) would be a rectangle from (3, 3) (top-left) to (10, 10) (bottom-right).)

As an example, rectIntersection(Rect(3, 3, 10 10), Rect(6, 6, 12, 12)) would return Rect(6, 6, 10, 10), while rectIntersection(Rect(4, 4, 5, 5), Rect(6, 6, 10 10)) would return null.

19 Upvotes

46 comments sorted by

View all comments

1

u/ctdonath Aug 13 '12

Canonical C++:

class Rect;
Rect rectIntersection( Rect&, Rect& );

class Rect
{
private:
	Rect();
	double x1, y1, x2, y2;
public:
	Rect( double _x1, double _y1, double _x2, double _y2 );
	bool operator==( Rect& right );
	bool valid();
friend Rect rectIntersection( Rect&, Rect& );
};

Rect::Rect( double _x1, double _y1, double _x2, double _y2 )
: x1(_x1), y1(_y1), x2(_x2), y2(_y2)
{
}

bool Rect::operator==( Rect& right )
{
	return 
		x1 == right.x1 &&
		y1 == right.y1 &&
		x2 == right.x2 &&
		y2 == right.y2;
}
bool Rect::valid() 
{ 
	return x1<=x2 && y1<=y2; 
}

Rect rectIntersection( Rect& r1, Rect& r2 )
{
	return Rect( 
		(r1.x1>r2.x1)?r1.x1:r2.x1, 
		(r1.y1>r2.y1)?r1.y1:r2.y1,
		(r1.x2<r2.x2)?r1.x2:r2.x2,
		(r1.y2<r2.y2)?r1.y2:r2.y2 );
}

0

u/ctdonath Aug 13 '12 edited Aug 13 '12

Obfuscated C++:

class Rect rectIntersection( Rect&, Rect& );
class Rect{ double l,u,r,d;
public:	
Rect(double L,double U,double R,double D): l(L),u(U),r(R),d(D){}
bool operator==(Rect& _){return l==_.l&&u==_.u&&r==_.r&&d==_.d;}
bool valid(){return l<=r&&u<=d;}
friend Rect rectIntersection(Rect&,Rect&);
} rectIntersection(Rect& a,Rect& b){return Rect((a.l>b.l)?a.l:b.l,(a.u>b.u)?a.u:b.u,(a.r<b.r)?a.r:b.r,(a.d<b.d)?a.d:b.d);}

(Insofar as a task this simple can be obfuscated.)