Skip to content

Commit 91b6494

Browse files
committed
Refactored files, removed main func, added tests.
Signed-off-by: Jobin John <[email protected]>
1 parent 1127456 commit 91b6494

File tree

2 files changed

+51
-18
lines changed

2 files changed

+51
-18
lines changed

strings/naiveStringSearch.go renamed to strings/naivesearch/naiveStringSearch.go

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,11 @@ Time Complexity : O(n*m)
88
m = length of pattern
99
*/
1010

11-
package main
12-
13-
import (
14-
"fmt"
15-
)
11+
package naivesearch
1612

1713
func naivePatternSearch(text string, pattern string) []int {
1814
var positions []int
19-
for i := 0; i < len(text)-len(pattern); i++ {
15+
for i := 0; i <= len(text)-len(pattern); i++ {
2016
var match bool = true
2117
for j := 0; j < len(pattern); j++ {
2218
if text[i+j] != pattern[j] {
@@ -31,15 +27,3 @@ func naivePatternSearch(text string, pattern string) []int {
3127
}
3228
return positions
3329
}
34-
35-
func main() {
36-
text := "ABAAABCDBBABCDDEBCABC"
37-
pattern := "ABC"
38-
var positions []int = naivePatternSearch(text, pattern)
39-
if len(positions) == 0 {
40-
fmt.Printf("Pattern not found in given text!")
41-
} else {
42-
fmt.Printf("Pattern found in following position:\n")
43-
fmt.Printf("%v", positions)
44-
}
45-
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package naivesearch
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
var testCases = []struct {
9+
name string
10+
input string
11+
pattern string
12+
expected []int
13+
}{
14+
{
15+
"string with multiple pattern matches",
16+
"ABAAABCDBBABCDDEBCABC",
17+
"ABC",
18+
[]int{4, 10, 18},
19+
},
20+
{
21+
"string with single pattern match",
22+
"ABCDEFGHIJKLMN",
23+
"CDE",
24+
[]int{2},
25+
},
26+
{
27+
"string with no pattern match",
28+
"ABCDEFGHIJKLMN",
29+
"XYZ",
30+
[]int(nil),
31+
},
32+
{
33+
"empty string",
34+
"",
35+
"XYZ",
36+
[]int(nil),
37+
},
38+
}
39+
40+
func TestNaivePatternSearch(t *testing.T) {
41+
for _, tc := range testCases {
42+
t.Run(tc.name, func(t *testing.T) {
43+
actual := naivePatternSearch(tc.input, tc.pattern)
44+
if !reflect.DeepEqual(actual, tc.expected) {
45+
t.Errorf("Expected matches for pattern '%s' for string '%s' are: %v, but actual matches are: %v", tc.pattern, tc.input, tc.expected, actual)
46+
}
47+
})
48+
}
49+
}

0 commit comments

Comments
 (0)