2

这段代码找到了两个矩形的交集,但我无法完全理解它。当我尝试将它映射到纸上时,它甚至没有形成一个矩形:

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]]. 有人可以解释这个过程吗?

4

1 回答 1

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>>
于 2013-10-18T06:09:11.137 回答