gpt4 book ai didi

ruby - 这段代码如何找到矩形交点?

转载 作者:数据小太阳 更新时间:2023-10-29 08:23:21 24 4
gpt4 key购买 nike

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

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]]。有人可以解释一下过程吗?

最佳答案

有时,查看编写的代码略有不同会有所帮助:

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>>

关于ruby - 这段代码如何找到矩形交点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com