ruby - Query Mongoid for all circle areas that include a given point -
let have 2 classes:
class cirle include mongoid::document field :lat, type: float field :lon, type: float field :radius, type: integer end class point include mongoid::document field :lat, type: float field :lon, type: float end
how can find circles include given point?
i'm not familiar mongoid
, perhaps following help. suppose:
circles = [ { x: 1, y: 2, radius: 3 }, { x: 3, y: 1, radius: 2 }, { x: 2, y: 2, radius: 4 }, ]
and
point = { x: 4.5, y: 1 }
then circles containing point
obtained of math::hypot:
circles.select { |c| math.hypot((c[:x]-point[:x]).abs, (c[:y]-point[:y]).abs) <= c[:radius] } #=> [{ x: 3, y: 1, radius: 2 }, { x: 2, y: 2, radius: 4 }]
edit: improve efficiency @drenmi suggests:
x, y = point.values_at(:x, :y) circles.select |c| d0, d1, r = (c[:x]-x).abs, (c[:y]-y).abs, c[:radius] d0*d0 + d1*d1 <= r*r end
Comments
Post a Comment