我很难找到一个好的算法来获取坐标系中一个点(包括中点)周围的所有点。
例子:
1 1 2 1 3 1
1 2 2 2 3 2
1 3 2 3 3 3
我有上面的网格,所以例如如果我输入: get_around_coordinates(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
我希望有人能给我比这更好的东西。
最佳答案
使用 Array#product :
def get_around_coordinates(px, py, radius)
xs = (px - radius..px + radius).to_a
ys = (py - radius..py + radius).to_a
xs.product(ys)
end
现在让我们假设 Ruby 缺少这个方法。功能方法将是 OOP 列表理解(flat_map + [flat_map ...] + map):xs.flat_map { |x| ys.map { |y| [x, y] } }
.
关于ruby - 获取点周围的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23907395/