Eugen
Eugen

Reputation: 155

Get Coordinates around a point

I have trouble to find a good algorithm to get all points around a point(the mid point included) in a coordinate system.

Example:

  1 1   2 1   3 1

  1 2   2 2   3 2

  1 3   2 3   3 3

I have the above grid, so for example if I input: get_around_coordinates(2, 2, 1)

It would return an array which would look like this [[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [2, 3], [3, 1], [3,2], [3, 3]]

This is how my method looks like:

 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

I hope that someone can give me something better than this.

Upvotes: 2

Views: 410

Answers (2)

tokland
tokland

Reputation: 67850

Using 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

Now let's imagine Ruby lacked this method. The functional approach would be a OOP list-comprehension (flat_map + [flat_map...] + map): xs.flat_map { |x| ys.map { |y| [x, y] } }.

Upvotes: 10

kostja
kostja

Reputation: 61538

a rather crude method

  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

Upvotes: 0

Related Questions