Refactor Permutations in EnumerableExtensions, add PermutationsWithRepeats method, and update tests for improved validation and clarity

This commit is contained in:
Sebastian Lindemeier
2025-12-16 07:56:20 +01:00
parent 0665713725
commit 9d4051ece1
2 changed files with 71 additions and 26 deletions
@@ -68,7 +68,7 @@ public static class EnumerableExtensions
}
}
public static IEnumerable<TValue[]> Permutations<TValue>(this IEnumerable<TValue> values, int count)
public static IEnumerable<TValue[]> PermutationsWithRepeats<TValue>(this IEnumerable<TValue> values, int count)
{
var pool = values.ToArray();
if (count > pool.Length)
@@ -96,6 +96,47 @@ public static class EnumerableExtensions
}
}
public static IEnumerable<TValue[]> Permutations<TValue>(this IEnumerable<TValue> values, int count)
{
var pool = values.ToArray();
var poolLength = pool.Length;
if (count > poolLength)
yield break;
var indices = Enumerable.Range(0, poolLength).ToArray();
var cycles = Enumerable.Range(0, poolLength + 1)
.Skip(poolLength - count + 1)
.Reverse()
.ToArray();
yield return GetCombination(indices[..count], pool);
var notDone = true;
while (notDone)
{
notDone = false;
for (var i = count - 1; i >= 0; i--)
{
cycles[i] -= 1;
if (cycles[i] == 0)
{
var tmp = indices[i];
for (var j = i; j < indices.Length - 1; j++)
{
indices[j] = indices[j + 1];
}
indices[^1] = tmp;
cycles[i] = poolLength - i;
}
else
{
var j = cycles[i];
(indices[i], indices[^j]) = (indices[^j], indices[i]);
yield return GetCombination(indices[..count], pool);
notDone = true;
break;
}
}
}
}
private static TValue[] GetCombination<TValue>(int[] innerIndices, TValue[] innerPool) =>
innerIndices.Select(i => innerPool[i]).ToArray();
}