Skip to content

Commit

Permalink
WordOccurrenceCounter: Implement thread-safe word counting
Browse files Browse the repository at this point in the history
  • Loading branch information
adwitkow committed Jan 18, 2025
1 parent 58f1d42 commit 1c750a1
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 6 deletions.
27 changes: 27 additions & 0 deletions Task1/WordOccurrenceCounter.Tests/WordCounterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace WordOccurrenceCounter.Tests;

public class WordCounterTests
{
[Test]
public void AddToCount_Parallel_ShouldCountCorrectly()
{
var wordCounter = new WordCounter();
var words = new[] { "test", "example", "parallel", "test", "example", "test" };
int iterations = 1000;

Parallel.For(0, iterations, i =>
{
foreach (var word in words)
{
wordCounter.AddToCount(word);
}
});

Assert.Multiple(() =>
{
Assert.That(wordCounter.GetCount("test"), Is.EqualTo(iterations * 3));
Assert.That(wordCounter.GetCount("example"), Is.EqualTo(iterations * 2));
Assert.That(wordCounter.GetCount("parallel"), Is.EqualTo(iterations * 1));
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\WordOccurrenceCounter\WordOccurrenceCounter.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
Expand Down
10 changes: 10 additions & 0 deletions Task1/WordOccurrenceCounter/IWordCounter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace WordOccurrenceCounter;

public interface IWordCounter
{
void AddToCount(string word);

int GetCount(string word);

IReadOnlyDictionary<string, int> GetCounts();
}
30 changes: 24 additions & 6 deletions Task1/WordOccurrenceCounter/WordCounter.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace WordOccurrenceCounter;

public class WordCounter
public class WordCounter : IWordCounter
{
private const int InitialValue = 1;

private readonly ConcurrentDictionary<string, int> _wordCounts;

public WordCounter()
{
_wordCounts = new ConcurrentDictionary<string, int>();
}

public void AddToCount(string word)
{
_wordCounts.AddOrUpdate(word, _ => InitialValue, (_, count) => count + 1);
}

public int GetCount(string word)
{
return _wordCounts.TryGetValue(word, out var count) ? count : 0;
}

public IReadOnlyDictionary<string, int> GetCounts()
{
return _wordCounts;
}
}

0 comments on commit 1c750a1

Please sign in to comment.