fork download
  1. class Hash
  2. def nearest3(j)
  3. 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]]
  4. end
  5. end
  6.  
  7. class Hash
  8. def nearest(j)
  9. self[self.keys.sort_by{ |i| Array.new(i.length){ |x| (i[x] - j[x]).abs}.inject{ |a, b| a -= -b}}[0]]
  10. end
  11. end
  12. class Hash #end55rpg
  13. def nearest2 ( array )
  14. self.sort { |a,b|a [ 0 ] [ 0 ] <=> array [ 0 ] } [ 0..2 ].sort { |a,b|a [ 0 ] [ 1 ] <=>array [ 1 ] } [ 0 ]
  15. end
  16. end
  17. require 'benchmark'
  18. a={}
  19. 1000.times{a[b=[rand(1000),rand(1000)]]=b}
  20. n = 15
  21. z=Array.new(n){[rand(1000),rand(1000)]}
  22. Benchmark.bm(7) do |x|
  23. x.report("mine") { z.each{ |i| print a.nearest i} }
  24. x.report("mine2") { z.each{ |i| print a.nearest3 i} }
  25. x.report("[]") { z.each{ |i| a[i]} }
  26. end
Success #stdin #stdout 0.08s 5024KB
stdin
Standard input is empty
stdout
             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)