Skip to content

Instantly share code, notes, and snippets.

@awhit012
Last active August 29, 2015 14:13
Show Gist options
  • Save awhit012/bd87074f29348ccc6393 to your computer and use it in GitHub Desktop.
Save awhit012/bd87074f29348ccc6393 to your computer and use it in GitHub Desktop.
A brute force pattern matching algorithm that works right to left on the pattern, in ruby
#Brute Force Right to Left
# Function accepts a string and a pattern to find in that string
def brute_search_2 string, pattern
pattern_length = pattern.length
# Iterate through the string starting at string[pattern_length-1]
# We are starting there because we are looking for matches in the pattern starting
# at the last char.
for string_index in (pattern_length - 1 ... string.length)
match_count = 0
loop do
# if a non-match is found, then break.
break if string[string_index - match_count] != pattern[(pattern_length - 1 - match_count)]
# if it wasn't a non-match, it must be a match!
match_count += 1
# if that match_count reaches the lenght of the pattern, you found the pattern!
# return the index in string where the pattern begins
return string_index - (pattern_length - 1) if match_count == pattern_length
end
end
return "not found"
end
# tests
puts " "
puts "Brute Force Right to Left Test:"
puts " "
# match
test_string = "let them eat cake"
test_pattern = "cake"
should_be = 13
result = brute_search_2 test_string, test_pattern
puts "Pattern at index #{result} "
raise "This is wrong" unless result == should_be
# no match
test_string2 = "let them eat cake"
test_pattern2 = "potato"
should_be2 = "not found"
result2 = brute_search_2 test_string2, test_pattern2
puts "Pattern at index #{result2} "
raise "This is wrong" unless result == should_be
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment