加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – Ruby中的矩形交集

发布时间:2020-12-17 04:02:25 所属栏目:百科 来源:网络整理
导读:我正在努力理解这个程序,但我遇到了一些困难.我不理解x_min,y_min,x_max,y_max的部分. 我理解程序通过两个带有左下角和右上角坐标的矩形,但是数组索引[0] [0],[1] [1]等来自何处? 我对发生的事情感到困惑,所以解释会有所帮助. # Write a function,`rec_inte
我正在努力理解这个程序,但我遇到了一些困难.我不理解x_min,y_min,x_max,y_max的部分.

我理解程序通过两个带有左下角和右上角坐标的矩形,但是数组索引[0] [0],[1] [1]等来自何处?

我对发生的事情感到困惑,所以解释会有所帮助.

# 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.
#
# Difficulty: 4/5
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

puts rec_intersection(
      [[0,0],[2,1]],[[1,[3,1]]
    ) == [[1,1]]

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


puts rec_intersection(
      [[1,[[4,4],5]]
    ) == nil

puts rec_intersection(
      [[1,4]],[[2,2],5]]
    ) == [[2,4]]

解决方法

What I don’t get in particular is the part with x_min,y_max. I get the the program passes through 2 rectangles with the bottom left and top right coordinate points. But where do the array indices come from? [0][0],[1][1],etc?

上面评论的这一部分代码对于理解这一点非常重要:

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

因此,如果rect是一个矩形,则rect [0]表示左下角,rect [1]表示右上角.此外,rect [0] [0]表示左下角的x坐标,rect [0] [1]是该角的y坐标,依此类推.

这部分评论也很重要:

# 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. [...]

如果rect是矩形,则该矩形的最左侧x坐标是左下角的x坐标.如上所述,rect [0] [0]表示左下角的x坐标.所以,在这一行:

x_min = [rect1[0][0],rect2[0][0]].max

rect1 [0] [0]和rect2 [0] [0]是矩形的两个最左边的x坐标,这行代码表示两个矩形的交叉点最左边的x坐标是等于其中任何一个更大.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读