Refactor Day02 travel distance calculation to use SlidingWindow

This commit is contained in:
Sebastian Lindemeier committed 2026-12-02 10:19:47 +01:00
1 parent d22fd3cacb
commit fefdc59bd8
2 files changed
+17 -8

No files matched your search

@@ -148,6 +148,15 @@ public static class EnumerableExtensions
private static TValue[] GetCombination<TValue>(int[] indices, TValue[] values) =>
indices.Select(i => values[i]).ToArray();
/// <summary>
/// Enumerates sliding windows over the sequence, yielding one array for each source element.
/// Each returned array contains the most recent values up to <paramref name="count"/>, so the initial windows may contain fewer than <paramref name="count"/> elements.
/// </summary>
/// <typeparam name="TValue">The type of elements in the sequence.</typeparam>
/// <param name="values">The sequence to enumerate.</param>
/// <param name="count">The maximum number of elements to include in each window.</param>
/// <returns>A sequence of arrays representing consecutive windows from <paramref name="values"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is less than zero.</exception>
public static IEnumerable<TValue[]> SlidingWindow<TValue>(this IEnumerable<TValue> values, int count)
{
var queue = new Queue<TValue>(count);
@@ -156,7 +165,7 @@ public static class EnumerableExtensions
queue.Enqueue(value);
if(queue.Count > count)
queue.Dequeue();
yield return queue.ToArray();
yield return [.. queue];
}
}
}