After this:

On 9/16/07, steve d <oksteev / yahoo.com> wrote:
> Here's my submission.  It's almost exactly the same as Jesus'.
[...]
> while low <= high
[...]

and this:

On 9/16/07, Eugene Kalenkovich <rubify / softover.com> wrote:
> BTW, all solutions already submitted will lie for subnets 1,2 and 5 :)
> Most (but not all) will break on out of bounds submissions (256.256.256.256
> or 0.0.0.-1, latter if comments are stripped out)

I made a couple of modifications to my code. Here is the latest version:

require 'ftools'

ip = ARGV[0].split(/\./)
ip = ip[0].to_i * 16777216 + ip[1].to_i * 65536 + ip[2].to_i * 256 + ip[3].to_i
file = ARGV[1] || 'ipdb.csv'

File.open(file) do |f|
  low = 0
  high = f.stat.size
  f.seek(high / 2)
  while low < high
    while (((a = f.getc) != 10) && (f.pos > 2))
        f.seek(-2, IO::SEEK_CUR)
    end
    pos = f.pos
    line = f.readline.split(",")
    low_range = line[0][1..-2].to_i
    high_range = line[1][1..-2].to_i
    if (low_range > ip)
      high = pos
      offset = (f.pos - pos) + ((high - low) / 2)
      f.seek(-offset, IO::SEEK_CUR)
    elsif (high_range < ip)
      low = f.pos
      f.seek((high-low) / 2, IO::SEEK_CUR)
    else
      puts line[4][1..-2]
      exit
    end
  end
  puts "No country found"
end

I changed to while low < high, and also the walking backwards failed
when reading the first line (btw, Steve, won't your solution also fail
for that case?).

Now:


time ruby quiz139b.rb 2.1.1.1
No country found

real    0m0.030s
user    0m0.016s
sys     0m0.004s

time ruby quiz139b.rb 5.1.1.1
No country found

real    0m0.032s
user    0m0.008s
sys     0m0.008s

time ruby quiz139b.rb 1.1.1.1
No country found

real    0m0.033s
user    0m0.016s
sys     0m0.000s

time ruby quiz139b.rb 256.256.256.256
No country found

real    0m0.096s
user    0m0.008s
sys     0m0.000s

Thanks,

Jesus.