Question

Write a function, rec_intersection(rect1, rect2) and returns the intersection of the two.

Rectangles are represented as a pair of coordinate-pairs: the bottom-left and top-right coordinates (given in [x, y] notation).

Hint: You can calculate the left-most x coordinate of the intersection by taking the maximum of the left-most x coordinate of each rectangle. Likewise, you can calculate the top-most y coordinate of the intersection by taking the minimum of the top most y coordinate of each rectangle

This is the answer:

def rec_intersection(rect1, rect2)
  x_min = [rect1[0][0], rect2[0][0]].max
  x_max = [rect1[1][0], rect2[1][0]].min

  y_min = [rect1[0][1], rect2[0][1]].max
  y_max = [rect1[1][1], rect2[1][1]].min

  return nil if ((x_max < x_min) || (y_max < y_min))
  return [[x_min, y_min], [x_max, y_max]]
end

Can someone help explain this code? At least a bit of guidance on the few points where to start deconstructing this code so I can get a start. I've never seen a problem like this one and have been struggling to understand it for the past hour and just can't make any headway.

Was it helpful?

Solution

The intersection of two rectangles is the rectangle where the two overlap. Because of that, you want a rectangle with:

  • The rightmost of the left-hand sides,
  • The leftmost of the right-hand sides,
  • The bottommost of the tops, and
  • The topmost of the bottoms.

In other words, you want the left, right, top, and bottom that are the closest to the center, but calculating it that way is excessive. So, those are your four x_min (et al) lines.

However, if the rectangles don't overlap at all, there isn't an intersection. That's your return nil line. How do we know there's no overlap? The right and left or the top and bottom aren't where we expect them to be.

The last line just assembles the coordinates (from the first four lines) into the upper-left and lower-right points as specified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top