Skip to content

Instantly share code, notes, and snippets.

@HoyaBoya
Created June 24, 2013 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoyaBoya/5850946 to your computer and use it in GitHub Desktop.
Save HoyaBoya/5850946 to your computer and use it in GitHub Desktop.
# attempt to perform hash based string search
# http://en.wikipedia.org/wiki/Rabin–Karp_algorithm
class HashStringSearch
def search(pattern, target)
table = {}
# loop through the target string, building position matches for the candidate
for i in 0 .. target.size
candidate = target[i .. i + pattern.size - 1]
table[candidate] ||= []
table[candidate] << i
end
table[pattern] || []
end
end
require "test/unit"
class HashStringSearchTest < Test::Unit::TestCase
def setup
@hash_string_search = HashStringSearch.new
end
def test_search
assert_search_equals("ABC", "ABDABEABC")
assert_search_equals("BOOM!", "HELLO WORLD")
end
def test_multiple_search
results = @hash_string_search.search("ABC", "ABCABDABC")
assert_equal 2, results.size
assert_equal [0, 6], results
end
protected
def assert_search_equals(pattern, target)
assert_equal target.index(pattern), @hash_string_search.search(pattern, target).first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment