Skip to content

Commit

Permalink
Adding KMP and adding rerevelant unit test.
Browse files Browse the repository at this point in the history
Resolving Sharpach#9
  • Loading branch information
Zohaib Sharani committed Oct 2, 2018
1 parent 9e7288d commit e4b879d
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Xunit;

namespace Algorithms.Tests
{
public class KnuthMorrisPrattTests
{
[Fact]
public void FunctionalityCheck()
{
var result = KnuthMorrisPratt.KnuthMorrisPratt.KMPSearch("AKMPAKMPCAADAKMPAKMPAA", "AKMPA");
Assert.NotEmpty(result);
Assert.Equal(3, result.Count);
Assert.Equal(0, result[0]);
Assert.Equal(12, result[1]);
Assert.Equal(16, result[2]);
}

[Fact]
public void EmptyCheck()
{
var result = KnuthMorrisPratt.KnuthMorrisPratt.KMPSearch("AKMPACAADAKMPKMP", "ASD");
Assert.Empty(result);
}
}
}
82 changes: 82 additions & 0 deletions Algorithms/Algorithms/KnuthMorrisPratt/KnuthMorrisPratt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms.KnuthMorrisPratt
{
public class KnuthMorrisPratt
{
public static List<int> KMPSearch(string text, string searchWord)
{
var result = new List<int>();
var txtLength = text.Length;
var wordLength = searchWord.Length;

int[] prefixPattren = new int[wordLength];
LongestPrefixPattren(searchWord, prefixPattren);

int wordIterator = 0;
int textIterator = 0;
while (textIterator<txtLength)
{
if (searchWord[wordIterator] == text[textIterator])
{
textIterator++;
wordIterator++;
}

if (wordIterator == wordLength)
{
result.Add(textIterator - wordIterator);
wordIterator = prefixPattren[wordIterator - 1];
}
else if (textIterator < txtLength && searchWord[wordIterator] != text[textIterator])
{
if (wordIterator != 0)
{
wordIterator = prefixPattren[wordIterator - 1];
}
else
{
textIterator++;
}
}
}

return result;
}

private static void LongestPrefixPattren(string searchWord, int[] prefixPattren)
{
var len = 0;
var i = 1;
prefixPattren[0] = 0;
var searchWordLength = searchWord.Length;


while (i< searchWordLength)
{
if (searchWord[i] == searchWord[len])
{
len++;
prefixPattren[i] = len;
i++;
}
else
{
if (len != 0)
{
len = prefixPattren[len - 1];
}
else
{
prefixPattren[i] = len;
i++;
}
}
}
}
}
}

0 comments on commit e4b879d

Please sign in to comment.