Last active
August 31, 2024 12:53
-
-
Save Artromskiy/876ee870529576c2c01e7ea1ac42c40f to your computer and use it in GitHub Desktop.
C# Span Extensions. Distinct elements, Count of repetitions per element. Useful when count of elements is less than 300
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace Utilities; | |
public static class SpanExtensions | |
{ | |
public static int Distinct<T>(this Span<T> items) | |
{ | |
EqualityComparer<T> comparer = EqualityComparer<T>.Default; | |
int count = items.Length; | |
int lastNonDuplicate = 0; | |
for (int i = 0; i < count; i++) | |
{ | |
var item = items[i]; | |
for (int j = 0; j < lastNonDuplicate; j++) | |
if (comparer.Equals(item, items[j])) | |
goto end; | |
items[lastNonDuplicate++] = item; | |
end:; | |
} | |
return lastNonDuplicate; | |
} | |
public static int CountRepetitions<T>(this ReadOnlySpan<T> items, Span<(T key, int count)> repeatCount) | |
{ | |
EqualityComparer<T> comparer = EqualityComparer<T>.Default; | |
int count = items.Length; | |
int lastNonDuplicate = 0; | |
for (int i = 0; i < count; i++) | |
{ | |
var item = items[i]; | |
for (int j = 0; j < lastNonDuplicate; j++) | |
if (comparer.Equals(item, repeatCount[j].key)) | |
{ | |
repeatCount[j].count++; | |
goto end; | |
} | |
repeatCount[lastNonDuplicate++] = (item, 1); | |
end:; | |
} | |
return lastNonDuplicate; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment