Extract Combinations method to AdventOfCode.Extensions and refactor usages to improve modularity and reduce duplication

This commit is contained in:
Sebastian Lindemeier
2025-12-12 12:35:01 +01:00
parent d92293f631
commit d0b612154a
7 changed files with 75 additions and 69 deletions
+2 -45
View File
@@ -6,6 +6,7 @@ using System.Data.Common;
using System.IO;
using System.Linq;
using AdvenOfCode.Contracts;
using AdventOfCode.Extensions;
using Microsoft.Z3;
namespace AoC_2025;
@@ -214,7 +215,7 @@ public class Day10 : IPuzzleSolver<long>
yield return ([..Enumerable.Repeat(0, patternLength)], 0);
for (var i = 1; i <= buttons.Length; i++)
{
foreach (var buttonPattern in Combinations(buttons, i))
foreach (var buttonPattern in buttons.Combinations(i))
{
var joltageLevels = GetJoltageLevelsForButtonPattern(patternLength, buttonPattern);
yield return (joltageLevels, buttonPattern.Length);
@@ -271,50 +272,6 @@ public class Day10 : IPuzzleSolver<long>
var answer = answerExpression is IntNum number ? number.Int64 : 0;
return answer;
}
private IEnumerable<TValue[]> Combinations<TValue>(IEnumerable<TValue> values, int count)
{
var pool = values.ToArray();
var poolLength = pool.Length;
if (count > poolLength)
yield break;
var indices = Range(0, count).ToArray();
yield return GetCombination(indices, pool);
while (true)
{
var validIndex = false;
var currentIndex = 0;
foreach (var i in Range(0, count).Reverse())
{
currentIndex = i;
if (indices[i] != i + poolLength - count)
{
validIndex = true;
break;
}
}
if(!validIndex)
yield break;
indices[currentIndex] += 1;
foreach (var j in Range(currentIndex + 1, count))
{
Index ix = j - 1;
indices[j] = indices[ix] + 1;
}
yield return GetCombination(indices, pool);
}
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;
}
}
}
public class IntArrayEqualityComparer : IEqualityComparer<int[]>