Skip to content

Commit ad5800f

Browse files
Jatin7385thuva4
andauthored
Rabin_Karp Code in Cpp (thuva4#889)
* Rabin_Karp Code in Cpp Commit * Rename algorithms/C++/RabinKarp_String_Matching/RabinKarp.cpp to algorithms/C++/RabinKarp/RabinKarp.cpp Co-authored-by: Thuvarakan Tharmarajasingam <17289840+Thuva4@users.noreply.github.com>
1 parent 9d93339 commit ad5800f

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

CONTRIBUTING.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,3 +181,4 @@ Unfortunately, sometimes the bug can be only reproduced in your project or in yo
181181
- [ir2010](https://github.com/ir2010)
182182
- [Cc618](https://github.com/Cc618)
183183
- [Md Azharuddin](https://github.com/azhar1038)
184+
- [Jatin7385](https://github.com/Jatin7385)
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
//Rabin Karp Implementation in CPP
2+
// Code by Jatin Dhall
3+
#include <iostream>
4+
#include <cmath>
5+
using namespace std;
6+
7+
//Subtracting each character by 96 so that lowercase alphabets start from 1
8+
int calculateHash(string pattern)//Function to calculate the hash value of the pattern
9+
{
10+
int n = pattern.length();
11+
int hash = 0;
12+
for(int i=0;i<n;i++)
13+
{
14+
hash += ((pattern[i] - 96) * pow(10,(n-i-1))); // Formula to calculate the hash value while avoiding Spurious Hits
15+
}
16+
return hash;
17+
}
18+
19+
int check(string substring, string pattern)//Function to check whether the characters are same bw the pattern and the substring
20+
//(Substring is the string of length m, that had the same hash value as the pattern)
21+
{
22+
for(int i=0;i<pattern.length();i++)
23+
{
24+
if(pattern.at(i) != substring.at(i))
25+
{
26+
return 0;
27+
}
28+
}
29+
return 1;
30+
}
31+
32+
void search(string text,string pattern)//Function that conducts the pattern matching
33+
{
34+
int hash = calculateHash(pattern);
35+
int hash1;
36+
string substring;
37+
int n = text.length(),m = pattern.length();
38+
for(int i=0;i<n;i++)
39+
{
40+
hash1 = 0;
41+
substring = "";
42+
43+
if(n - i < m){break;}//Checking if the remaining no. of characters is less thn the length of the pattern
44+
45+
for(int j = 0; j<m;j++)//Calculating the hash value of the substring of length m from text
46+
{
47+
substring += text[i+j];
48+
hash1 += ((text[i + j] - 96) * pow(10,(m-j-1)));
49+
}
50+
if(hash == hash1) //If the hash value of the substring is the same as that of the pattern, then check each characters
51+
{
52+
int res = check(substring,pattern); // Check
53+
if(res == 1)
54+
{
55+
cout<<"Pattern found at : "<<i+1<<"'th Position"<<endl;
56+
}
57+
}
58+
}
59+
}
60+
61+
int main()
62+
{
63+
string text,pattern;
64+
cout<<"Enter the text : ";
65+
cin>>text;
66+
cout<<"Enter the pattern : ";
67+
cin>>pattern;
68+
search(text,pattern);
69+
70+
}

0 commit comments

Comments
 (0)