From fc47effb657776bbafdc10606e6618234ade8060 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Fri, 29 May 2020 08:00:58 -0400 Subject: [PATCH] document brute force string search --- strings/brute_force_string_searching.cpp | 89 ++++++++++++------------ 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 3288b36b0..9a2b5327a 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -1,52 +1,53 @@ -#include -#include -#include - -using std::string; - -int brute_force(string text, string pattern); -std::vector> test_set = { - // {text, pattern, expected output} - {"a", "aa", "-1"}, - {"a", "a", "0"}, - {"ba", "b", "0"}, - {"bba", "bb", "0"}, - {"bbca", "c", "2"}, - {"ab", "b", "1"} -}; - -int main() { - for (size_t i = 0 ; i < test_set.size(); i++) { - int output = brute_force(test_set[i][0], test_set[i][1]); - if (std::to_string(output) == test_set[i][2]) - std::cout << "success\n"; - else - std::cout << "failure\n"; - } - return 0; -} - -/* - *@description Find a pattern in a string by comparing the pattern - * to every substring. - *@param text Any string that might contain the pattern. - *@param pattern String that we are searching for. - *@return Index where the pattern starts in the text or - * -1 if the pattern was not found. +/** + * @file + * @brief String pattern search - brute force */ +#include +#ifdef _MSC_VER +#include // use this for MS Visucal C++ +#else +#include +#endif +#include -int brute_force(string text, string pattern) { - size_t pat_l = pattern.length(); - size_t txt_l = text.length(); - int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l-pat_l+1; i++) { - string s = text.substr(i, pat_l); - if (s == pattern) { - index = i; +/** + * Find a pattern in a string by comparing the pattern to every substring. + * @param text Any string that might contain the pattern. + * @param pattern String that we are searching for. + * @return Index where the pattern starts in the text + * @return -1 if the pattern was not found. + */ +int brute_force(const std::string &text, const std::string &pattern) { + size_t pat_l = pattern.length(); + size_t txt_l = text.length(); + int index = -1; + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + std::string s = text.substr(i, pat_l); + if (s == pattern) { + index = i; break; } } } return index; } + +/** set of test cases */ +const std::vector> test_set = { + // {text, pattern, expected output} + {"a", "aa", "-1"}, {"a", "a", "0"}, {"ba", "b", "0"}, + {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; + +/** Main function */ +int main() { + for (size_t i = 0; i < test_set.size(); i++) { + int output = brute_force(test_set[i][0], test_set[i][1]); + + if (std::to_string(output) == test_set[i][2]) + std::cout << "success\n"; + else + std::cout << "failure\n"; + } + return 0; +}