Skip to content

Instantly share code, notes, and snippets.

@abidkhan484
Last active October 24, 2024 09:46
Show Gist options
  • Save abidkhan484/d30fdfbd72e06ab0523b83204729d7f3 to your computer and use it in GitHub Desktop.
Save abidkhan484/d30fdfbd72e06ab0523b83204729d7f3 to your computer and use it in GitHub Desktop.
Concept of Rabin Karp Algorithm

Drawback: Spurious Hits

package main
import "fmt"
type pattern struct {
hashValue int
length int
}
var mapping = make(map[string]int)
func assignStringMap() {
for ch := 'A'; ch <= 'z'; ch++ {
mapping[string(ch)] = int(ch) - 64
}
}
func hashStringToInt(fullString string) pattern {
val := 0
for _, ch := range fullString {
val += mapping[string(ch)]
}
return pattern{
hashValue: val,
length: len(fullString),
}
}
func rabinKarpAlgo(fullString string, pattern pattern) bool {
length := pattern.length
hashValue := pattern.hashValue
val := 0
fullStringLength := len(fullString)
if length > fullStringLength {
return false
}
for i := range length {
ch := fullString[i]
val += mapping[string(ch)]
}
if val == hashValue {
return true
}
for i := length; i < fullStringLength; i++ {
firstChar := fullString[i-length]
currChar := fullString[i]
val = val + mapping[string(currChar)] - mapping[string(firstChar)]
if val == hashValue {
return true
}
}
return false
}
func main() {
assignStringMap()
pattern := "aaa"
fullString := "aaabc"
matchingStatus := rabinKarpAlgo(fullString, hashStringToInt(pattern))
if matchingStatus {
fmt.Println("String **matched** using Rabin Karp algorithm")
} else {
fmt.Println("String **not matched** using Rabin Karp algorithm")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment