Skip to content

Commit df3565a

Browse files
committed
Add Rabin-Karp Algorithm
1 parent 2818d68 commit df3565a

File tree

4 files changed

+56
-1
lines changed

4 files changed

+56
-1
lines changed

.travis.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ script:
1818
cd ../MergeSort && go test ./;
1919
cd ../SelectionSort && go test ./;
2020
cd ../TernarySearch && go test ./;
21-
cd ../NaiveStringSearch && go test ./;
21+
cd ../NaiveStringSearch && go test ./;
22+
cd ../RabinKarp && go test ./;

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ There are several data structures and algorithms implemented in this project. Th
2929
##### String searching algorithms
3030

3131
- Naive String Search
32+
- Rabin-Karp Algorithm
3233

3334
##### Sorting algorithms
3435
- Selection Sort

RabinKarp/RabinKarp.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package RabinKarp
2+
3+
import "hash/adler32"
4+
5+
func calculateHash(text string) uint32 {
6+
return adler32.Checksum([]byte(text))
7+
}
8+
9+
func RabinKarp(text, pattern string) int {
10+
textLength := len(text)
11+
patternLength := len(pattern)
12+
if patternLength > textLength {
13+
return -1
14+
}
15+
for i := 0; i < textLength-patternLength+1; i++ {
16+
if calculateHash(pattern) != calculateHash(text[i:i+patternLength]) {
17+
continue
18+
}
19+
matchesCount := 0
20+
for j := 0; j < patternLength; j++ {
21+
if text[i+j] != pattern[j] {
22+
break
23+
}
24+
matchesCount++
25+
}
26+
if matchesCount == patternLength {
27+
return i
28+
}
29+
}
30+
return -1
31+
}

RabinKarp/RabinKarp_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package RabinKarp
2+
3+
import (
4+
"math/rand"
5+
"testing"
6+
"time"
7+
)
8+
9+
func TestRabinKarp(t *testing.T) {
10+
random := rand.New(rand.NewSource(time.Now().UnixNano()))
11+
letters := []rune("abcdefghijklmnopqrstuvwxyz")
12+
text := make([]rune, random.Intn(15-10)+10)
13+
for i := range text {
14+
text[i] = letters[rand.Intn(len(letters))]
15+
}
16+
end := random.Intn(len(text)-5) + 5
17+
start := random.Intn(end)
18+
result := RabinKarp(string(text), string(text[start:end]))
19+
if result == -1 {
20+
t.Fail()
21+
}
22+
}

0 commit comments

Comments
 (0)