Skip to content

Add: kmp(Knuth-Morris-Pratt) algorithm #586

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 4, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,13 +418,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.

##### Functions:

1. [`Kmp`](./strings/kmp/kmp.go#L70): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. Prints whether the word/pattern was found and on what position in the text or not. m - current match in text, i - current character in w, c - amount of comparisons.

---
##### Types

1. [`Result`](./strings/kmp/kmp.go#L15): No description provided.

1. [`Kmp`](./strings/kmp/kmp.go#L4): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.

---
</details><details>
Expand Down
132 changes: 32 additions & 100 deletions strings/kmp/kmp.go
Original file line number Diff line number Diff line change
@@ -1,117 +1,49 @@
package kmp

import (
"fmt"
)

// User defined.
// Set to true to read input from two command line arguments
// Set to false to read input from two files "pattern.txt" and "text.txt"

// const isTakingInputFromCommandLine bool = true

const notFoundPosition int = -1

type Result struct {
resultPosition int
numberOfComparison int
}

// Implementation of Knuth-Morris-Pratt algorithm (Prefix based approach).
// Requires either a two command line arguments separated by a single space,
// or two files in the same folder: "pattern.txt" containing the string to
// be searched for, "text.txt" containing the text to be searched in.
// func main() {
// var text string
// var word string

// if isTakingInputFromCommandLine { // case of command line input
// args := os.Args
// if len(args) <= 2 {
// log.Fatal("Not enough arguments. Two string arguments separated by spaces are required!")
// }
// word = args[1]
// text = args[2]
// for i := 3; i < len(args); i++ {
// text = text + " " + args[i]
// }
// } else { // case of file input
// patFile, err := ioutil.ReadFile("../pattern.txt")
// if err != nil {
// log.Fatal(err)
// }
// textFile, err := ioutil.ReadFile("../text.txt")
// if err != nil {
// log.Fatal(err)
// }
// text = string(textFile)
// word = string(patFile)
// }
// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
func Kmp(word, text string, patternTable []int) []int {
if len(word) > len(text) {
return nil
}

// if len(word) > len(text) {
// log.Fatal("Pattern is longer than text!")
// }
// fmt.Printf("\nRunning: Knuth-Morris-Pratt algorithm.\n\n")
// fmt.Printf("Search word (%d chars long): %q.\n", len(word), word)
// fmt.Printf("Text (%d chars long): %q.\n\n", len(text), text)
var (
i, j int
matches []int
)
for i+j < len(text) {

// r := kmp(text, word)
// if r.resultPosition == notFoundPosition {
// fmt.Printf("\n\nWord was not found.\n%d comparisons were done.", r.numberOfComparison)
// } else {
// fmt.Printf("\n\nWord %q was found at position %d in %q. \n%d comparisons were done.", word,
// r.resultPosition, text, r.numberOfComparison)
// }
// }
if word[j] == text[i+j] {
j++
if j == len(word) {
matches = append(matches, i)

// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
// Prints whether the word/pattern was found and on what position in the text or not.
// m - current match in text, i - current character in w, c - amount of comparisons.
func Kmp(text string, word string) Result {
m, i, c := 0, 0, 0
t := kmpTable(word)
for m+i < len(text) {
fmt.Printf("\n comparing characters %c %c at positions %d %d", text[m+i], word[i], m+i, i)
c++
if word[i] == text[m+i] {
fmt.Printf(" - match")
if i == len(word)-1 {
return Result{
m, c,
}
i = i + j
j = 0
}
i++
} else {
m = m + i - t[i]
if t[i] > -1 {
i = t[i]
i = i + j - patternTable[j]
if patternTable[j] > -1 {
j = patternTable[j]
} else {
i = 0
j = 0
}
}
}
return Result{notFoundPosition,
c,
}
return matches
}

// Table building algorithm.
// Takes word to be analyzed and table to be filled.
func kmpTable(word string) (t []int) {
t = make([]int, len(word))
pos, cnd := 2, 0
t[0], t[1] = -1, 0
for pos < len(word) {
if word[pos-1] == word[cnd] {
cnd++
t[pos] = cnd
pos++
} else if cnd > 0 {
cnd = t[cnd]
} else {
t[pos] = 0
pos++
// Table building for kmp algorithm.
func Table(w string) []int {
var (
t []int = []int{-1}
k int
)
for j := 1; j < len(w); j++ {
k = j - 1
for w[0:k] != w[j-k:j] && k > 0 {
k--
}
t = append(t, k)
}
return t
}
87 changes: 48 additions & 39 deletions strings/kmp/kmp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,48 +5,57 @@ import (
"testing"
)

var testCases = []struct {
name string
word string
text string
expected Result
}{
{
"String comparison on single pattern match",
"announce",
"CPM_annual_conference_announce",
Result{
22,
32,
},
},
{
"String comparison on multiple pattern match",
"AABA",
"AABAACAADAABAABA",
Result{
0,
4,
},
},
{
"String comparison with not found pattern",
"AABC",
"AABAACAADAABAABA",
Result{
-1,
23,
func TestKmp(t *testing.T) {
type args struct {
word string
text string
patternTable []int
}
tests := []struct {
name string
args args
want []int
}{
{
name: "test1",
args: args{
word: "ab",
text: "ababacaab",
patternTable: Table("ababacaab"),
},
want: []int{0, 2, 7},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Kmp(tt.args.word, tt.args.text, tt.args.patternTable); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Kmp() = %v, want %v", got, tt.want)
}
})
}
}

func TestKMP(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual := Kmp(tc.text, tc.word)
if !reflect.DeepEqual(actual, tc.expected) {
t.Errorf("Expected matches for pattern '%s' for string '%s' are: %v steps at position %v, but actual matches are: %v steps at position %v",
tc.word, tc.text, tc.expected.numberOfComparison, tc.expected.resultPosition, actual.numberOfComparison, actual.resultPosition)
func TestTable(t *testing.T) {
type args struct {
w string
}
tests := []struct {
name string
args args
want []int
}{
{
name: "test1",
args: args{
w: "ababacaab",
},
want: []int{-1, 0, 0, 1, 2, 3, 0, 1, 1},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Table(tt.args.w); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Table() = %v, want %v", got, tt.want)
}
})
}
Expand Down