class Hash def nearest3(j) self[self.keys.select{|i|Array.new(i.length){ |x| (i[x] - j[x]).abs}.inject{ |a, b| a -= -b} <= 100}.sort_by{ |i| Array.new(i.length){ |x| (i[x] - j[x]).abs}.inject{ |a, b| a -= -b}}[0]] end end class Hash def nearest(j) self[self.keys.sort_by{ |i| Array.new(i.length){ |x| (i[x] - j[x]).abs}.inject{ |a, b| a -= -b}}[0]] end end class Hash #end55rpg def nearest2 ( array ) self.sort { |a,b|a [ 0 ] [ 0 ] <=> array [ 0 ] } [ 0..2 ].sort { |a,b|a [ 0 ] [ 1 ] <=>array [ 1 ] } [ 0 ] end end require 'benchmark' a={} 1000.times{a[b=[rand(1000),rand(1000)]]=b} n = 15 z=Array.new(n){[rand(1000),rand(1000)]} Benchmark.bm(7) do |x| x.report("mine") { z.each{ |i| print a.nearest i} } x.report("mine2") { z.each{ |i| print a.nearest3 i} } x.report("[]") { z.each{ |i| a[i]} } end
Standard input is empty
user system total real mine [317, 181][735, 636][207, 714][959, 670][160, 47][517, 901][666, 737][975, 747][902, 963][864, 672][459, 367][86, 943][165, 650][330, 640][745, 919] 0.040000 0.000000 0.040000 ( 0.043459) mine2 [317, 181][735, 636][207, 714][959, 670][160, 47][517, 901][666, 737][975, 747][902, 963][864, 672][459, 367][86, 943][165, 650][330, 640][745, 919] 0.030000 0.000000 0.030000 ( 0.029037) [] 0.000000 0.000000 0.000000 ( 0.000027)