Ruby中的矩形交集

cec*_*ode 4 ruby arrays intersection intersect

我正在努力理解这个程序,但我遇到了一些困难.我不理解的部分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, 0], [3, 1]]
    ) == [[1, 0], [2, 1]]

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


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

puts rec_intersection(
      [[1, 1], [5, 4]],
      [[2, 2], [3, 5]]
    ) == [[2, 2], [3, 4]]
Run Code Online (Sandbox Code Playgroud)

Gna*_*ale 8

变量x_min,x_max,y_min,y_max用于存储相交区域的坐标.他们正在使用获得max和min使用传入的矩形的两值阵列上.呼叫[1 ,2].max将返回2,并且呼叫[1,2].min将返回1例如.

这些变量代表交叉矩形的原因可能更容易通过图像理解(非常详细和专业的图表传入): 矩形与假人相交

如您所见,黄色(交叉)矩形的最小值不能小于红色矩形的最小值.最大值可以不小于蓝色矩形的最大值.

  • 好图,+ 1 :) (3认同)
  • 这只是一个小笑话 (2认同)