GotI received the following question in a technical interview today (for a devops/SRE position): Write a function which returns true if the two rectangles passed to it as arguments would overlap if drawn on a cartesian plane. The rectangles are guaranteed to be aligned with the axes, not arbitrarily rotated.
Write a function which returns true if the two rectangles passed to it as arguments would overlap if drawn on a Cartesian plane. The rectangles are guaranteed to be aligned with the axes, not arbitrarily rotated.
#/usr/bin/env python
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Rect(object):
def __init__(self, p1, p2):
'''Store the top, bottom, left and right values for points
p1 and p2 are the (corners) in either order
'''
self.left = min(p1.x, p2.x)
self.right = max(p1.x, p2.x)
self.bottom = min(p1.y, p2.y)
self.top = max(p1.y, p2.y)
#/usr/bin/env python
def overlap(r1,r2):
'''Overlapping rectangles overlap both horizontally & vertically
'''
hoverlaps = True
voverlaps = True
if (r1.left > r2.right) or (r1.right < r2.left):
hoverlaps = False
if (r1.top < r2.bottom) or (r1.bottom > r2.top):
voverlaps = False
return hoverlaps and voverlaps
This seems to work (for all my test cases) but it also looks wrong to me. My My initial attempt was to start with hoverlaps and voverlaps as False, and selectively set them to True using conditions similar to these shown (but with the inequality operators reversed).