CS153/hw5/hw4programs/kmp.oat
jmug 9224001a22 Update hw5 to a newer version.
Signed-off-by: jmug <u.g.a.mariano@gmail.com>
2025-01-24 21:10:31 -08:00

68 lines
1.4 KiB
Text

/* 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;
}