Created
October 26, 2009 13:45
-
-
Save banker/218645 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
equire 'benchmark' | |
class String | |
def ending | |
length = self.length | |
self[length-2].chr + self[length-1].chr | |
end | |
def base | |
self[0..(self.length-3)] | |
end | |
end | |
class EndingFinder | |
attr_reader :results | |
def initialize(filename) | |
@results = [] | |
@cache = {} | |
# For cache expiration. | |
@letter = "a" | |
File.open(filename).each do |word| | |
w = word.chomp.downcase.strip | |
process_word(w) if word.length > 2 | |
end | |
end | |
def process_word(word) | |
base = word.base | |
if @cache[base] | |
@cache[base].each do |ending| | |
if word.ending == ending.reverse | |
@results << [base + ending, word] | |
end | |
end | |
else | |
cache_word(base, word) | |
end | |
end | |
def cache_word(base, word) | |
if @current_letter != (letter = word[0].chr) | |
@cache = {} | |
@current_letter = letter | |
end | |
@cache[base] ||= [] | |
@cache[base] << word.ending | |
end | |
end | |
Benchmark.bm do |x| | |
x.report do | |
EndingFinder.new('web2down').results.each do |result| | |
puts result.join(' ') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment