这段代码如何找到矩形交集?

时间:2013-10-18 05:14:01

标签: ruby intersection

此代码找到两个矩形的交集,但我无法完全理解它。当我尝试将其映射到纸上时,它甚至不会形成矩形:

def rec_intersection(rect1, rect2)
  x_min = [rect1[0][0], rect2[0][1]].max
  x_max = [rect1[1][0], rect2[1][1]].min
  y_min = [rect1[0][0], rect2[0][1]].max
  y_max = [rect1[1][0], 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

rec_intersection([[1, 1], [2, 2]],[[0, 0], [5, 5]])

上面的代码返回[[1, 1], [2, 2]]。有人可以解释这个过程吗?

1 个答案:

答案 0 :(得分:7)

有时看到代码编写方式有所不同:

def rec_intersection(rect1, rect2)

  x_min = [rect1.top_left.x, rect2.top_left.x].max # => 1
  y_min = [rect1.top_left.y, rect2.top_left.y].max # => 1

  x_max = [rect1.bottom_right.x, rect2.bottom_right.x].min # => 2
  y_max = [rect1.bottom_right.y, rect2.bottom_right.y].min # => 2

  Rectangle.new(
    Point.new(x_min, y_min),
    Point.new(x_max, y_max)
  )

end

Point = Struct.new(:x, :y)
Rectangle = Struct.new(:top_left, :bottom_right)

rect1 = Rectangle.new(Point.new(1, 1), Point.new(2, 2))
# => #<struct Rectangle
#     top_left=#<struct Point x=1, y=1>,
#     bottom_right=#<struct Point x=2, y=2>>

rect2 = Rectangle.new(Point.new(0, 0), Point.new(5, 5))
# => #<struct Rectangle
#     top_left=#<struct Point x=0, y=0>,
#     bottom_right=#<struct Point x=5, y=5>>

rec_intersection(rect1, rect2)
# => #<struct Rectangle
#     top_left=#<struct Point x=1, y=1>,
#     bottom_right=#<struct Point x=2, y=2>>