ruby - 获取点周围的坐标

标签 ruby

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

例子:

  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/

相关文章:

基于 TCL 的 Expect 的 Ruby 版本?

ruby-on-rails - 运行测试时 ElasticSearch Rails resource_already_exists_exception

Ruby 类方法设置

ruby-on-rails - Ruby on Rails 中的多对多多态关联

ruby-on-rails - 启动同一作业的多个延迟作业进程

ruby-on-rails - 新 Rails 项目启动时丢失文件

ruby-on-rails - 记录的哈希表示中的嵌套属性

ruby-on-rails - 将类似的数组值合并到新的分组数组?

ruby-on-rails - Rspec.config 之前(:each) except for specific :types

ruby - 我的应用程序的基本 URL 是什么?