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)
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |