r/dailyprogrammer • • Aug 11 '12
[8/10/2012] Challenge #87 [easy] (Rectangle intersection)
Write a function that calculates the intersection 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.
View all comments
Show parent comment
2
u/[deleted] Aug 17 '12
You can define data structures like this
and get the
getXandgetYfunctions for free.Also, you could've defined rawIntersect as
which is probably easier than messing around with
(getX $ getLT r1)and the likes.And I think for some cases you'll have to compare both x and y coordinates when checking the result of the intersection:
(getX lt) > (getX rb) || (getY lt) > (getY rb)