Skip to content

Instantly share code, notes, and snippets.

@Artromskiy
Last active August 31, 2024 12:53
Show Gist options
  • Save Artromskiy/876ee870529576c2c01e7ea1ac42c40f to your computer and use it in GitHub Desktop.
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
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