Skip to content

Instantly share code, notes, and snippets.

@xarg
Created June 28, 2011 07:01
Show Gist options
  • Save xarg/1050644 to your computer and use it in GitHub Desktop.
Save xarg/1050644 to your computer and use it in GitHub Desktop.
Boyer-Moore-Horspool (Go)
package main
import (
"fmt"
)
func count_words(word, text string) int {
var skip [255]int
m := len(word)
n := len(text)
if m > n {
return 0
}
//Initializing skip table
for i := 0; i <= 254; i++ {
skip[i] = m
}
//Adding skip table values
for k := 0; k < m - 1; k++ {
skip[int(word[k])] = m - k - 1
}
k := m - 1
count := 0
for k < n {
j := m - 1
i := k
for j >= 0 && text[i] == word[j] { j--; i-- } //The matching process
if j == -1 { // Found a match, increase the counter and skip forward
//Calculate the begining of the word
begin := text[0]
if i > 0 {
begin = text[i]
}
//Calculate the end of the word
end := text[len(text) - 1]
if i + m + 1 < n {
end = text[i + m + 1]
}
//Check if it's a word
if (end == ' ' && i == -1 ) || (i == n - m - 1 && begin == ' ') || (begin == ' ' && end == ' ') {
count++
k += m - 1
continue
}
}
// No match found, skip forward
k += skip[text[k]]
}
return count
}
func main() {
//fmt.Printf("Position: %d\n", count_words("aaaa", "bbbbbbbb"))
fmt.Printf("Result: %d\n\n", count_words("aaaa", "bbbbbaaaaa"))
fmt.Printf("Result: %d\n", count_words("111",
"aaddaaaaa 11111aaaaaaaaaaddaaa"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment