Skip to content

Instantly share code, notes, and snippets.

@willnet
Created July 6, 2013 06:24
Show Gist options
  • Save willnet/5938892 to your computer and use it in GitHub Desktop.
Save willnet/5938892 to your computer and use it in GitHub Desktop.
tokyorubyistmeetupのペアプロ課題その1
# -*- coding: utf-8 -*-
require "csv"
module PostalCode
class << self
def sort
ary = CSV.read(File.join(File.dirname(__FILE__), "../data/ken_all.csv"))
sorted = ary.sort_by { |line| line[2] }
CSV.open("sorted.csv", "wb") do |csv|
sorted.each do |line|
csv << line
end
end
end
def find(postal_code)
searcher = Searcher.new(postal_code, csv)
match = searcher.search(0, csv.length - 1)
match && match[6,3]
end
private
def csv
@csv ||= CSV.read(File.join(File.dirname(__FILE__), "../data/sorted.csv"))
end
end
class Searcher
def initialize(postal_code, csv)
@csv = csv
@code = postal_code.tr("-", "")
end
def search(start_line, end_line)
half_line = (start_line + end_line) / 2
row = @csv[half_line]
if row[2] == @code
return row
end
if half_line <= 0 || half_line >= @csv.length - 1
return nil
end
if row[2] > @code
search(start_line, half_line - 1)
else row[2] < @code
search(half_line + 1, end_line)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment