Skip to content

Commit e9f1d40

Browse files
committed
Implement unit test for knuth morris pratt
1 parent b688264 commit e9f1d40

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
using Algorithms.Strings.Search;
3+
using Xunit;
4+
using Xunit.Abstractions;
5+
6+
namespace AlgorithmsUnitTest.Strings.Search
7+
{
8+
public class KnuthMorrisPrattUnitTest
9+
{
10+
11+
private ITestOutputHelper console;
12+
13+
public KnuthMorrisPrattUnitTest(ITestOutputHelper console)
14+
{
15+
this.console = console;
16+
}
17+
18+
[Fact]
19+
public void Test()
20+
{
21+
String text = "o fare thee well, poor devil of a Sub-Sub, whose commen- \n" + "tator I am. Thou belongest to that hopeless, sallow tribe \n"
22+
+ "which no wine of this world will ever warm ; and for whom \n" + "even Pale Sherry would be too rosy-strong ; but with whom \n"
23+
+ "one sometimes loves to sit, and feel poor-devilish, too ; and \n"
24+
+ "grow convivial upon tears ; and say to them bluntly with full \n" + "eyes and empty glasses, and in not altogether unpleasant \n"
25+
+ "sadness Give it up, Sub-Subs ! For by how much the more \n" + "pains ye take to please the world, by so much the more shall \n"
26+
+ "ye forever go thankless ! Would that I could clear out \n" + "Hampton Court and the Tuileries for ye ! But gulp down \n"
27+
+ "your tears and hie aloft to the royal-mast with your hearts ; \n" + "for your friends who have gone before are clearing out the \n"
28+
+ "seven-storied heavens, and making refugees of long-pampered \n" + "Gabriel, Michael, and Raphael, against your coming. Here \n"
29+
+ "ye strike but splintered hearts together there, ye shall \n" + "strike unsplinterable glasses! ";
30+
31+
KnuthMorrisPratt bm = new KnuthMorrisPratt("the");
32+
print("found at " + bm.Search(text));
33+
Assert.NotEqual(-1, bm.Search(text));
34+
}
35+
36+
private void print(String content)
37+
{
38+
Console.WriteLine(content);
39+
console.WriteLine(content);
40+
}
41+
}
42+
}

cs-algorithms/Strings/Search/KnuthMorrisPratt.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@ public KnuthMorrisPratt(string pat)
1313
{
1414
dfs[i] = new int[M];
1515
}
16-
dfs[0][0] = 1;
16+
dfs[pat[0]][0] = 1;
1717
int X = 0;
1818
for (var i = 1; i < M; ++i)
1919
{
20-
for (var r = 0; r < R; ++i)
20+
for (var r = 0; r < R; ++r)
2121
{
2222
dfs[r][i] = dfs[r][X];
2323
}
@@ -33,7 +33,7 @@ public int Search(string text)
3333
for (var i = 0; i < N; ++i)
3434
{
3535
X = dfs[text[i]][X];
36-
if (X == M) return i;
36+
if (X == M) return i-M+1;
3737
}
3838
return -1;
3939
}

0 commit comments

Comments
 (0)