TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
rabin_karp.cpp File Reference

The Rabin-Karp Algorithm for finding a pattern within a piece of text with complexity O(n + m) More...

#include <cassert>
#include <cmath>
#include <iostream>
#include <cstring>
Include dependency graph for rabin_karp.cpp:

Go to the source code of this file.

Namespaces

namespace  string_search
 

Macros

#define PRIME   5
 Prime modulus for hash functions.
 

Functions

int64_t string_search::create_hash (const std::string &s, int n)
 
int64_t string_search::recalculate_hash (const std::string &s, int old_index, int new_index, int64_t old_hash, int patLength)
 
bool string_search::check_if_equal (const std::string &str1, const std::string &str2, int start1, int end1, int start2, int end2)
 
int string_search::rabin_karp (const std::string &str, const std::string &pat)
 
int main (void)
 
int rabin_karp (const std::string &str, const std::string &pat)
 

Detailed Description

The Rabin-Karp Algorithm for finding a pattern within a piece of text with complexity O(n + m)

Definition in file rabin_karp.cpp.

Macro Definition Documentation

◆ PRIME

#define PRIME   5

Prime modulus for hash functions.

Definition at line 16 of file rabin_karp.cpp.

Function Documentation

◆ main()

int main ( void )

Main function

Definition at line 105 of file rabin_karp.cpp.

105 {
106 assert(rabin_karp("helloWorld", "world") == -1);
107 assert(rabin_karp("helloWorld", "World") == 5);
108 assert(rabin_karp("this_is_c++", "c++") == 8);
109 assert(rabin_karp("happy_coding", "happy") == 0);
110 return 0;
111}
int rabin_karp(const std::string &str, const std::string &pat)

◆ rabin_karp()

int string_search::rabin_karp ( const std::string & str,
const std::string & pat )

Perform string pattern search using Rabin-Karp algorithm

Parameters
[in]strstring to search in
[in]patpattern to search for
Returns
index of first occurrence of pattern
-1 if pattern not found

Definition at line 83 of file rabin_karp.cpp.

83 {
84 int64_t pat_hash = create_hash(pat, pat.size());
85 int64_t str_hash = create_hash(str, pat.size());
86 for (int i = 0; i <= str.size() - pat.size(); ++i) {
87 if (pat_hash == str_hash &&
88 check_if_equal(str, pat, i, i + pat.size() - 1, 0,
89 pat.size() - 1)) {
90 return i;
91 }
92 if (i < str.size() - pat.size()) {
93 str_hash =
94 recalculate_hash(str, i, i + pat.size(), str_hash, pat.size());
95 }
96 }
97 return -1; // return -1 if given pattern not found
98}
int64_t create_hash(const std::string &s, int n)
bool check_if_equal(const std::string &str1, const std::string &str2, int start1, int end1, int start2, int end2)
int64_t recalculate_hash(const std::string &s, int old_index, int new_index, int64_t old_hash, int patLength)