Last active
December 18, 2015 21:28
-
-
Save HoyaBoya/5847071 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
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