Skip to content

Instantly share code, notes, and snippets.

@julio73
Created March 6, 2014 23:06
Show Gist options
  • Save julio73/9401681 to your computer and use it in GitHub Desktop.
Save julio73/9401681 to your computer and use it in GitHub Desktop.
Fun ruby exercise on 2D coords
# Output the closest n points to a random point from a pool of m 2-D coordinates.
# All coordinates are within the domain range 0..d
# m may be be smaller than n
def closest_2d_coords(n = 5, m = 100, d = 100)
rand2d_gen = ->(d) { 2.times.map { (rand*d).round }}
cartesian_distance =
->(c1, c2) { ((c1[0] - c2[0])**2 + (c1[1] - c2[1])**2)**0.5 }
ref_pt = rand2d_gen.call(d)
coords = m.times.map { rand2d_gen.call(d)}
selection = []
coords.each_with_index do |coord_pt, idx|
dst = cartesian_distance.call(ref_pt, coord_pt)
entry = selection.find_index { |e| e.first >= dst}
if entry
selection.insert(entry, [dst, idx])
selection.pop if selection.size > n
else
selection.push([dst, idx]) if selection.size < n
end
end
closests = selection.map { |e| coords[e.last]}
puts "Reference point: #{ ref_pt }\n",
"Closest #{ n } points:\n #{ closests }\n",
"Pool coordinates:\n #{ coords }"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment