2

このコードは 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 に答える