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/robin-gvx 0 2 Aug 15 '12
rect l t r b:
	& & l t & r b

get-l:
	&< &<

get-t:
	&> &<

get-r:
	&< &>

get-b:
	&> &>

max a b:
	if > a b:
		a
	else:
		b

min a b:
	if < a b:
		a
	else:
		b

print-rect r:
	if r:
		print( "rect " get-l r " " get-t r " " get-r r " " get-b r )
	else:
		print "none"

overlap r1 r2:
	local :l max get-l r1 get-l r2
	local :t max get-t r1 get-t r2
	local :r min get-r r1 get-r r2
	local :b min get-b r1 get-b r2
	if or > l r > t b:
		false
	else:
		rect l t r b

print-rect overlap rect 3 3 10 10 rect 6 6 12 12
print-rect overlap rect 4 4 5 5 rect 6 6 10 10

prints

rect 6 6 10 10
none