Skip to content

Instantly share code, notes, and snippets.

@HoyaBoya
Last active December 18, 2015 21:28
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/5847071 to your computer and use it in GitHub Desktop.
Save HoyaBoya/5847071 to your computer and use it in GitHub Desktop.
class StringSearch
# naive string search implementation
def search(pattern, text)
pattern_array = pattern.split(//)
text_array = text.split(//)
for i in 0 .. text_array.size - 1
match_count = 0
for j in 0 .. pattern_array.size - 1
# keep incrementing match count for every matching character
if text_array[i + j] == pattern_array[j]
match_count += 1
else
break
end
end
# we found a match since count equals pattern size
if match_count == pattern_array.size
return i
end
end
return nil
end
end
require "test/unit"
class StringSearchTest < Test::Unit::TestCase
def test_search
assert_equal "hello there!".index("lo"), StringSearch.new.search("lo", "hello there!")
assert_equal "hello there!".index("miss!"), StringSearch.new.search("miss!", "hello there!")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment