In: Computer Science
Python: A rectangle is axis-aligned if its sides are parallel to
the coordinate axes. An axis-aligned rectangle will be defined by
its bottom left corner (x,y), its (nonnegative) width w, and its
(nonnegative) height h. The Cartesian coordinates (x,y) behave in
the normal mathematical way: increasing x moves right, increasing y
moves up. (In future, we will see situations where different
conventions are used.)
Write the function rOverlap that tests whether 2 axis-aligned
rectangles overlap. rOverlap takes 8 floats (x1,y1,w1,y1 represent
the first rectangle and x2,y2,w2,y2 represent the second rectangle)
and returns True if the two rectangles overlap/touch, even if only
at a single point, and False otherwise.
Context. Detection of the overlap of bounding boxes is used in
collision detection (e.g., robotics, games). A bounding box of an
object is a rectangle (2D) or box (higher dimensions) that contains
the object. Since two objects can collide only if their bounding
boxes overlap, collision detection of bounding boxes is used as an
efficient test, with the more expensive intersection of the objects
used only in the rare cases when the bounding boxes overlap.
Collision detection is used during motion planning of a robot, or
interactively during a game to prevent, say, running through walls.
Observation. It would be more elegant to collapse the 8 parameters
of this function into two rectangle parameters, but that requires
more advanced Python syntax. You may revisit these functions once
we have that power.
Code:
def rOverlap(x1,y1,w1,h1,x2,y2,w2,h2):
bottomLeft1 = (x1,y1)
bottomRight1 = (x1 + w1,y1)
topLeft1 = (x1,y1 + h1)
topRight1 = (x1 + w1,y1 + h1)
bottomLeft2 = (x2,y2)
bottomRight2 = (x2 + w2,y2)
topLeft2 = (x2,y2 + h2)
topRight2 = (x2 + w2,y2 + h2)
rect1 = [bottomLeft1,bottomRight1,topLeft1,topRight1]
rect2 = [bottomLeft2,bottomRight2,topLeft2,topRight2]
#If any two co-ordinates match, then return true
for i in rect1:
for j in rect2:
if i == j:
return True
#If one rectangle is to the side of other
if bottomRight2[0] < topLeft1[0] or topLeft2[0] >
bottomRight1[0]:
return False
#If one rectangle is on the top of other
if bottomRight2[1] > topLeft1[1] or topLeft2[1] <
bottomRight1[1]:
return False
#If both the conditions fail
return True
#Test
x1 = 0
y1 = 0
h1 = 10
w1 = 10
x2 = 5
y2 = 5
h2 = 3
w2 = 3
print(rOverlap(x1,y1,w1,h1,x2,y2,w2,h2))
The output of the above code is True for the given test case.
Please appreciate the solution if you find it helpful.
If you have any doubts in the solution, feel free to ask me in the comment section.