Ruby 获取点周围的坐标

Ruby 获取点周围的坐标,ruby,Ruby,我很难找到一个好的算法来获得坐标系中一个点(包括中点)周围的所有点 例如: 1 1 2 1 3 1 1 2 2 2 3 2 1 3 2 3 3 3 我有上面的网格,例如,如果我输入: 在_坐标(2,2,1)周围获取_ 它将返回一个如下所示的数组 [1,1]、[2,1]、[3,1]、[1,2]、[2,2]、[2,3]、[3,1]、[3,2]、[3,3]] 我的方法是这样的: def get_around_coordinates(px, py, radiu

我很难找到一个好的算法来获得坐标系中一个点(包括中点)周围的所有点

例如:

  1 1   2 1   3 1

  1 2   2 2   3 2

  1 3   2 3   3 3
我有上面的网格,例如,如果我输入: 在_坐标(2,2,1)周围获取_

它将返回一个如下所示的数组 [1,1]、[2,1]、[3,1]、[1,2]、[2,2]、[2,3]、[3,1]、[3,2]、[3,3]]

我的方法是这样的:

 def get_around_coordinates(px, py, radius)
    coord = []
    start_x = px - radius
    start_y = py - radius
    (radius * 2 + 1).times do |x|
      (radius * 2 + 1).times do |y|
        coord.push([start_x + x, start_y + y])
      end
    end
    return coord
  end
我希望有人能给我比这更好的东西。

使用:

现在让我们想象一下Ruby缺少这种方法。函数方法将是OOP列表理解(flat_-map+[flat_-map…]+map):
xs.flat_-map{| x | ys.map{| y |[x,y]}

一种相当粗糙的方法

  def neighborhood(x=0, y=0, radius)
    (x-radius..x+radius).reduce([]) { |neighbors, x1|
      (y-radius..y+radius).each { |y1| neighbors << [x1, y1] }
      neighbors
    }
  end
def邻域(x=0,y=0,半径)
(x-半径..x+半径)。减少([]){|邻域,x1|

(y-radius..y+radius)。每个{y1}邻域可以让你澄清“更好”。更快?更简洁?你绝对需要完整的数组,还是一个
枚举器会有用?定义
get_around_坐标
(需要三个参数)如何与
get_坐标
(需要两个参数)相关不需要将
转换为_a
。还要注意的是,必须使用
减少
+
每个
=功能性的
平面图
+
(OOP排序列表理解)。
  def neighborhood(x=0, y=0, radius)
    (x-radius..x+radius).reduce([]) { |neighbors, x1|
      (y-radius..y+radius).each { |y1| neighbors << [x1, y1] }
      neighbors
    }
  end