|
| 1 | +## |
| 2 | +# This class represents a table of {bad_match_character => slide_offset} |
| 3 | +# to be used in Boyer-Moore-Horspool substring finding algorithm. |
| 4 | + |
| 5 | +class BadMatchTable |
| 6 | + |
| 7 | + attr_reader :pattern |
| 8 | + attr_reader :table |
| 9 | + |
| 10 | + def initialize(pattern) |
| 11 | + @pattern = pattern |
| 12 | + @table = {} |
| 13 | + for i in 0...pattern.size |
| 14 | + @table[pattern[i]] = pattern.size - 1 - i |
| 15 | + end |
| 16 | + end |
| 17 | + |
| 18 | + ## |
| 19 | + # Given a mismatch character belonging to the search string, returns |
| 20 | + # the offset to be used when sliding the pattern towards the right. |
| 21 | + |
| 22 | + def slide_offset(mismatch_char) |
| 23 | + table.fetch(mismatch_char, pattern.size) |
| 24 | + end |
| 25 | +end |
| 26 | + |
| 27 | +## |
| 28 | +# Returns the first starting index of the given pattern's occurrence (as a substring) |
| 29 | +# in the provided search string if a match is found, -1 otherwise. |
| 30 | + |
| 31 | +def first_match_index(search_string, pattern) |
| 32 | + matches = matches_indices(search_string, pattern, true) |
| 33 | + matches.empty? ? -1 : matches[0] |
| 34 | +end |
| 35 | + |
| 36 | +## |
| 37 | +# Returns the list of starting indices of the given pattern's occurrences (as a substring) |
| 38 | +# in the provided search string. |
| 39 | +# If no match is found, an empty list is returned. |
| 40 | +# If `stop_at_first_match` is provided as `true`, the returned list will contain at most one element, |
| 41 | +# being the leftmost encountered match in the search string. |
| 42 | + |
| 43 | +def matches_indices(search_string, pattern, stop_at_first_match=false) |
| 44 | + table = BadMatchTable.new(pattern) |
| 45 | + i = pattern.size - 1 |
| 46 | + indices = [] |
| 47 | + while i < search_string.size |
| 48 | + for j in 0...pattern.size |
| 49 | + if search_string[i-j] != pattern[pattern.size-1-j] |
| 50 | + i += table.slide_offset(search_string[i-j]) |
| 51 | + break |
| 52 | + elsif j == pattern.size-1 |
| 53 | + indices.append(i-j) |
| 54 | + return indices if stop_at_first_match |
| 55 | + i += 1 |
| 56 | + end |
| 57 | + end |
| 58 | + end |
| 59 | + indices |
| 60 | +end |
0 commit comments