Refactor `EnumerableExtensions` to simplify combination generation by removing `Range` method and streamlining index logic

This commit is contained in:
Sebastian Lindemeier 2025-12-15 10:44:38 +01:00
parent ee061757a8
commit 56521d39d7
1 changed files with 9 additions and 20 deletions

View File

@ -12,29 +12,24 @@ public static class EnumerableExtensions
var poolLength = pool.Length;
if (count > poolLength)
yield break;
var indices = Range(0, count).ToArray();
var indices = Enumerable.Range(0, count).ToArray();
yield return GetCombination(indices, pool);
while (true)
{
var validIndex = false;
var currentIndex = 0;
for(var i = count - 1; i >= 0; i--)
int idx;
for(idx = count - 1; idx >= 0; idx--)
{
currentIndex = i;
if (indices[i] != i + poolLength - count)
{
validIndex = true;
var isIndexBelowMax = indices[idx] != idx + poolLength - count;
if (isIndexBelowMax)
break;
}
}
if(!validIndex)
if(idx < 0)
yield break;
indices[currentIndex] += 1;
foreach (var j in Range(currentIndex + 1, count))
indices[idx] += 1;
for (var j = idx + 1; j < count; j++)
{
Index ix = j - 1;
indices[j] = indices[ix] + 1;
indices[j] = indices[j - 1] + 1;
}
yield return GetCombination(indices, pool);
@ -42,11 +37,5 @@ public static class EnumerableExtensions
static TValue[] GetCombination(int[] innerIndices, TValue[] innerPool) =>
innerIndices.Select(i => innerPool[i]).ToArray();
static IEnumerable<int> Range(int start, int end)
{
for (var i = start; i < end; i++)
yield return i;
}
}
}