Skip to content

Commit 2818d68

Browse files
committed
Add Naive String Search
1 parent 7df0fb1 commit 2818d68

File tree

4 files changed

+52
-1
lines changed

4 files changed

+52
-1
lines changed

.travis.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ script:
1717
cd ../LinearSearch && go test ./;
1818
cd ../MergeSort && go test ./;
1919
cd ../SelectionSort && go test ./;
20-
cd ../TernarySearch && go test ./;
20+
cd ../TernarySearch && go test ./;
21+
cd ../NaiveStringSearch && go test ./;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package NaiveStringSearch
2+
3+
func NaiveStringSearch(text, pattern string) int {
4+
textLength := len(text)
5+
patternLength := len(pattern)
6+
if patternLength > textLength {
7+
return -1
8+
}
9+
for i := 0; i < textLength-patternLength+1; i++ {
10+
matchesCount := 0
11+
for j := 0; j < patternLength; j++ {
12+
if text[i+j] != pattern[j] {
13+
break
14+
}
15+
matchesCount++
16+
}
17+
if matchesCount == patternLength {
18+
return i
19+
}
20+
}
21+
return -1
22+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package NaiveStringSearch
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"testing"
7+
"time"
8+
)
9+
10+
func TestNaiveStringSearch(t *testing.T) {
11+
random := rand.New(rand.NewSource(time.Now().UnixNano()))
12+
letters := []rune("abcdefghijklmnopqrstuvwxyz")
13+
text := make([]rune, random.Intn(15-5)+5)
14+
for i := range text {
15+
text[i] = letters[rand.Intn(len(letters))]
16+
}
17+
end := random.Intn(len(text)-5) + 5
18+
start := random.Intn(end)
19+
fmt.Println(len(text), end, start)
20+
result := NaiveStringSearch(string(text), string(text[start:end]))
21+
if result == -1 {
22+
t.Fail()
23+
}
24+
}

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ There are several data structures and algorithms implemented in this project. Th
2626
- Exponential Search
2727
- Ternary Search
2828

29+
##### String searching algorithms
30+
31+
- Naive String Search
32+
2933
##### Sorting algorithms
3034
- Selection Sort
3135
- Insertion Sort

0 commit comments

Comments
 (0)