-
Notifications
You must be signed in to change notification settings - Fork 292
/
RabinKarp.cs
76 lines (60 loc) · 2.03 KB
/
RabinKarp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
namespace Advanced.Algorithms.String;
/// <summary>
/// A Rabin-Karp string search implementation.
/// </summary>
public class RabinKarp
{
/// <summary>
/// Hard coding this, ideally should be a large prime
/// To reduce collisions.
/// </summary>
private const int PrimeNumber = 101;
private readonly double tolerance = 0.00001;
public int Search(string input, string pattern)
{
var patternHash = ComputeHash(pattern);
var hash = ComputeHash(input.Substring(0, pattern.Length));
if (Math.Abs(hash - patternHash) < tolerance)
if (Valid(pattern, input.Substring(0, pattern.Length)))
return 0;
var lashHash = hash;
for (var i = 1; i < input.Length - pattern.Length + 1; i++)
{
var newHash = ComputeHash(lashHash, pattern.Length, input[i - 1],
input[i + pattern.Length - 1]);
if (Math.Abs(newHash - patternHash) < tolerance)
if (Valid(pattern, input.Substring(i, pattern.Length)))
return i;
lashHash = newHash;
}
return -1;
}
/// <summary>
/// Returns true if matched hash string is same as the pattern.
/// </summary>
private bool Valid(string pattern, string match)
{
return pattern.Equals(match);
}
/// <summary>
/// Compute hash given a string.
/// </summary>
private double ComputeHash(string input)
{
double result = 0;
for (var i = 0; i < input.Length; i++) result += input[i] * Math.Pow(PrimeNumber, i);
return result;
}
/// <summary>
/// Compute hash given a newChar and last hash.
/// </summary>
private double ComputeHash(double lastHash, int patternLength,
char removedChar, char newChar)
{
lastHash -= removedChar;
var newHashHash = lastHash / PrimeNumber
+ newChar * Math.Pow(PrimeNumber, patternLength - 1);
return newHashHash;
}
}