added namespace string_search

This commit is contained in:
Krishna Vedala 2020-05-31 23:09:10 -04:00
parent 5a2615c54e
commit fd69530515
3 changed files with 143 additions and 129 deletions

View File

@ -10,6 +10,7 @@
#endif
#include <vector>
namespace string_search {
/**
* Find a pattern in a string by comparing the pattern to every substring.
* @param text Any string that might contain the pattern.
@ -32,6 +33,9 @@ int brute_force(const std::string &text, const std::string &pattern) {
}
return index;
}
} // namespace string_search
using string_search::brute_force;
/** set of test cases */
const std::vector<std::vector<std::string>> test_set = {

View File

@ -20,6 +20,7 @@
#endif
#include <vector>
namespace string_search {
/**
* Generate the partial match table aka failure function for a pattern to
* search.
@ -64,6 +65,9 @@ bool kmp(const std::string &pattern, const std::string &text) {
}
return false;
}
} // namespace string_search
using string_search::kmp;
/** Main function */
int main() {

View File

@ -15,6 +15,7 @@
#define PRIME 5 ///< Prime modulus for hash functions
namespace string_search {
/**
* convert a string to an intger - called as hashing function
* \param[in] s source of string to hash
@ -42,7 +43,8 @@ int64_t recalculate_hash(const std::string& s, int old_index, int new_index,
int64_t old_hash, int patLength) {
int64_t new_hash = old_hash - s[old_index];
new_hash /= PRIME;
new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1));
new_hash +=
(int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1));
return new_hash;
}
@ -89,13 +91,17 @@ int rabin_karp(const std::string& str, const std::string& pat) {
return i;
}
if (i < str.size() - pat.size()) {
str_hash =
recalculate_hash(str, i, i + pat.size(), str_hash, pat.size());
str_hash = recalculate_hash(str, i, i + pat.size(), str_hash,
pat.size());
}
}
return -1; // return -1 if given pattern not found
}
} // namespace string_search
using string_search::rabin_karp;
/** Main function */
int main(void) {
assert(rabin_karp("helloWorld", "world") == -1);