File tree Expand file tree Collapse file tree 4 files changed +56
-1
lines changed
Expand file tree Collapse file tree 4 files changed +56
-1
lines changed Original file line number Diff line number Diff 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 ./;
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments