Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace RabinKarpSubstringSearch
- {
- using System;
- class Program
- {
- private const int Prime = 31;
- static void Main(string[] args)
- {
- Console.WriteLine("Hello World!");
- string pattern = "foo";
- int patternHash = CalcHash(pattern);
- int pos = IsMatch("hello _foobar", patternHash, pattern.Length);
- if (pos != 1)
- {
- Console.WriteLine("Tadaaa! " + pos);
- }
- Console.ReadLine();
- }
- private static int CalcHash(string pattern)
- {
- int hashValue = 0;
- int len = pattern.Length;
- //for (int i = 0; i < len; i++)
- //{
- // hashValue += Convert.ToInt32(pattern[i]) * (int)Math.Pow(Prime, i);
- //}
- int i = 0;
- while (i < len)
- {
- hashValue += Convert.ToInt32(pattern[i]) * (int)Math.Pow(Prime, i);
- i++;
- }
- return hashValue;
- }
- private static int IsMatch(string text, int patternHash, int lenPattern)
- {
- int i = 0;
- // compute 1st hash from 0 to lenghth of pattern -1
- int textHash = 0;
- while (i < lenPattern)
- {
- textHash += Convert.ToInt32(text[i]) * (int)Math.Pow(Prime, i);
- i++;
- }
- // check match found at position 0
- if (patternHash == textHash)
- {
- return 0;
- }
- // compute and comparing the the hashes
- int len = text.Length;
- while (i < len)
- {
- int k = i;
- // note: this is quite easy to understand
- // https://www.youtube.com/watch?v=H4VrKHVG5qI&t=324s
- textHash = (textHash - Convert.ToInt32(text[i - lenPattern])) / Prime + Convert.ToInt32(text[i]) * (int)Math.Pow(Prime, lenPattern - 1);
- if (patternHash == textHash)
- {
- // return the index. k is index of last letter in pattern so return back length of pattern - 1 (-1 is that we are already in the last letter of the pattern)
- return k - lenPattern - 1;
- }
- i++;
- }
- return -1;
- }
- }
- }
- // explanation: https://www.youtube.com/watch?v=H4VrKHVG5qI&t=324s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement