边界检查笛卡尔坐标系

时间:2015-06-20 09:13:14

标签: ruby

我有一个固定尺寸的笛卡尔平面

WIDTH, HEIGHT = 10, 20

我想确定表示为有序对的点是否是该平面的边或角。例如,[0, 0][9, 19]是角落; [0, 5][6, 19]是边缘。

这是我的代码:

# max allowable x and y coordinates
MAXX = WIDTH - 1
MAXY = HEIGHT - 1

# is this coordinate at the corner of the plane?
def corner?(*coords)
  coords.uniq == [0]     || # lower-left corner
  coords == [MAXX, MAXY] || # upper-right corner
  coords == [MAXX, 0]    || # lower-right corner
  coords == [0, MAXY]       # upper-left corner
end

# is this coordinate at the edge of the plane?
def edge?(*coords)
  return (
    (
      coords.include?(0)  || # if x or y coordinate is at
      coords[0] == MAXX  || # its min or max, the coordinate
      coords[1] == MAXY     # is an edge coordinate
    ) && 
    !corner?(coords) # it's not an edge if it's a corner
  )
end

它给出了这些结果,我希望如此:

corner?(0, 0) #=> true
corner?(0, 5) #=> false
edge?(0, 5)   #=> true
corner?(5, 5) #=> false
edge?(5, 5)   #=> false

但是,我期待以下内容:

edge?(0, 0) #=> true

它给出了

edge?(0, 0)   #=> false

我做错了什么?

1 个答案:

答案 0 :(得分:0)

请注意,在edge?方法中,您正在呼叫:

def edge?(*coords)
  #...
  !corner?(coords)
end

其中coords是单Array,即您正在呼叫corner?([0, 0]),而不是corner?(0, 0)。相反,扩展这样的参数:

def edge?(*coords)
  #...
  !corner?(*coords)
end