Change hw6 to an unsolved version.
Signed-off-by: jmug <u.g.a.mariano@gmail.com>
This commit is contained in:
parent
0c04936ccf
commit
ee01a8f5b2
186 changed files with 9605 additions and 4019 deletions
68
hw6/hw4programs/kmp.oat
Normal file
68
hw6/hw4programs/kmp.oat
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/* Paul Lou and Tanner Haldeman */
|
||||
/* References: Algorithms (Sedgewick), https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm */
|
||||
|
||||
int[] construct_table(string w) {
|
||||
var length = length_of_string(w);
|
||||
var arr_of_w = array_of_string(w);
|
||||
var t = new int[length];
|
||||
var curr = 2;
|
||||
var next = 0;
|
||||
|
||||
t[0] = -1;
|
||||
t[1] = 0;
|
||||
while (curr < length) {
|
||||
if (arr_of_w[curr-1] == arr_of_w[next]) {
|
||||
t[curr] = next + 1;
|
||||
next = next + 1;
|
||||
curr = curr + 1;
|
||||
}
|
||||
else if (next > 0) {
|
||||
next = t[next];
|
||||
}
|
||||
else {
|
||||
t[curr] = 0;
|
||||
curr = curr + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
|
||||
int kmp(string str, string w) {
|
||||
var str_idx = 0;
|
||||
var word_idx = 0;
|
||||
var word_length = length_of_string(w);
|
||||
var word_arr = array_of_string(w);
|
||||
var str_arr = array_of_string(str);
|
||||
var t = construct_table(w);
|
||||
|
||||
while (str_idx + word_idx < length_of_string(str)) {
|
||||
if (word_arr[word_idx] == str_arr[str_idx + word_idx]) {
|
||||
if (word_idx == word_length - 1) {
|
||||
return str_idx;
|
||||
}
|
||||
word_idx = word_idx + 1;
|
||||
}
|
||||
else {
|
||||
if (t[word_idx] > -1) {
|
||||
str_idx = str_idx + word_idx - t[word_idx];
|
||||
word_idx = t[word_idx];
|
||||
}
|
||||
else {
|
||||
str_idx = str_idx + 1;
|
||||
word_idx = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int program(int argc, string[] argv) {
|
||||
var str = "abcdabcdabcdcbab";
|
||||
var word = "dabcdc";
|
||||
|
||||
var ret = kmp(str, word);
|
||||
return ret;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue