In [1]:
t := "haystack needle haystack" // "text" - thing we search in
p := "needle" // "pattern" - thing we search for
In [2]:
func naive(p, t string) []int {
// assume len(p) <= len(t)
occurrences := []int{}
for i := 0; i < len(t) - len(p) + 1; i++ { // for each alignment of p to t
match := true // assume we match until proven wrong
for j := 0; j < len(p); j++ { // for each position of p
if t[i+j] != p[j] {
match = false // at least 1 char mismatches
break
}
}
if match {
occurrences = append(occurrences, i)
}
}
return occurrences
}
In [3]:
naive(p, t)
Out[3]:
In [4]:
t[9:9+len(p)]
Out[4]:
In [5]:
naive("needle", "needleneedleneedle")
Out[5]: