Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions csharp-advanced-topics/UsingTrieForPatternSearch/Tests/Test.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Buffers;
using UsingTrieForPatternSearch;

namespace Tests
Expand Down Expand Up @@ -205,5 +206,80 @@ public void WhenPatternInTextMultipleTimes_ThenSortedListSearch_ReturnsTrue()

Assert.Equal(expected, actual);
}

[Fact]
public void WhenPatternInText_ThenTrieContainsPattern_ReturnsTrue()
{
var trie = new Trie();
trie.AddWord("dc");
trie.AddWord("xyz");

var actual = trie.ContainsPattern("abcdefghijklmnopqrstuvwxyz");

Assert.True(actual);
}

[Fact]
public void WhenPatternNotInText_ThenTrieContainsPattern_ReturnsFalse()
{
var trie = new Trie();
trie.AddWord("dc");

var actual = trie.ContainsPattern("abcdefghijklmnopqrstuvwxyz");

Assert.False(actual);
}

[Fact]
public void WhenGivenPrefix_ThenGetWordsWithPrefix_ReturnsEveryWordBelowIt()
{
var trie = new Trie();

foreach (var word in new[] { "cat", "car", "cart", "dog" })
{
trie.AddWord(word);
}

var actual = trie.GetWordsWithPrefix("ca");

Assert.Equal(new[] { "car", "cart", "cat" }, actual.Order());
}

[Fact]
public void WhenPrefixNotInTrie_ThenGetWordsWithPrefix_ReturnsEmpty()
{
var trie = new Trie();

foreach (var word in new[] { "cat", "car", "cart", "dog" })
{
trie.AddWord(word);
}

var actual = trie.GetWordsWithPrefix("x");

Assert.Empty(actual);
}

[Fact]
public void WhenRunningBenchmarks_ThenEveryMethodFindsThePatternEveryTime()
{
var benchmark = new PatternSearchBenchmark();
benchmark.Setup();

Assert.Equal(1000000, benchmark.TrieSearch());
Assert.Equal(1000000, benchmark.HashSetSearch());
Assert.Equal(1000000, benchmark.ListSearch());
Assert.Equal(1000000, benchmark.StringContainsSearch());
}

[Fact]
public void WhenUsingSearchValues_ThenContainsAny_FindsPattern()
{
var patterns = SearchValues.Create(["dc", "xyz"], StringComparison.Ordinal);

var actual = "abcdefghijklmnopqrstuvwxyz".AsSpan().ContainsAny(patterns);

Assert.True(actual);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<PackageReference Include="coverlet.collector" Version="10.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,88 @@

namespace UsingTrieForPatternSearch
{
[InProcess]
public class PatternSearchBenchmark
{
private const string _text = "abcdefghijklmnopqrstuvwxyz";
private const string _pattern = "cd";
private const int _iterations = 1000000;
private readonly Trie _trie;
private readonly Trie _trie = new Trie();

public PatternSearchBenchmark()
[GlobalSetup]
public void Setup()
{
_trie = new Trie();
_trie.AddWord(_pattern);
}

[Benchmark]
public void TrieSearch()
public int TrieSearch()
{
var found = 0;

for (int i = 0; i < _iterations; i++)
{
_trie.Search(_text);
if (_trie.ContainsPattern(_text))
found++;
}

return found;
}

[Benchmark]
public void HashSetSearch()
public int HashSetSearch()
{
var found = 0;

for (int i = 0; i < _iterations; i++)
{
HashSetPatternSearcher.Search(_text, _pattern);
if (HashSetPatternSearcher.Search(_text, _pattern))
found++;
}

return found;
}

[Benchmark]
public void ListSearch()
public int ListSearch()
{
var found = 0;

for (int i = 0; i < _iterations; i++)
{
ListPatternSearcher.Search(_text, _pattern);
if (ListPatternSearcher.Search(_text, _pattern))
found++;
}

return found;
}

[Benchmark]
public void SortedListSearch()
public int SortedListSearch()
{
var found = 0;

for (int i = 0; i < _iterations; i++)
{
SortedListPatternSearcher.Search(_text, _pattern);
if (SortedListPatternSearcher.Search(_text, _pattern))
found++;
}

return found;
}

[Benchmark]
public int StringContainsSearch()
{
var found = 0;

for (int i = 0; i < _iterations; i++)
{
if (_text.Contains(_pattern, StringComparison.Ordinal))
found++;
}

return found;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,53 @@ public bool Search(string word)

return node.IsWord;
}

public bool ContainsPattern(string text)
{
for (int start = 0; start < text.Length; start++)
{
var node = _root;

for (int i = start; i < text.Length; i++)
{
if (!node.Children.TryGetValue(text[i], out var next))
break;

node = next;

if (node.IsWord)
return true;
}
}

return false;
}

public List<string> GetWordsWithPrefix(string prefix)
{
var words = new List<string>();
var node = _root;

foreach (char c in prefix)
{
if (!node.Children.TryGetValue(c, out var next))
return words;

node = next;
}

CollectWords(node, prefix, words);

return words;
}

private static void CollectWords(TrieNode node, string word, List<string> words)
{
if (node.IsWord)
words.Add(word);

foreach (var (c, child) in node.Children)
CollectWords(child, word + c, words);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.5" />
<PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
</ItemGroup>

</Project>
Loading