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) => private static TValue[] GetCombination<TValue>(int[] indices, TValue[] values) =>
indices.Select(i => values[i]).ToArray(); 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) public static IEnumerable<TValue[]> SlidingWindow<TValue>(this IEnumerable<TValue> values, int count)
{ {
var queue = new Queue<TValue>(count); var queue = new Queue<TValue>(count);
@@ -156,7 +165,7 @@ public static class EnumerableExtensions
queue.Enqueue(value); queue.Enqueue(value);
if(queue.Count > count) if(queue.Count > count)
queue.Dequeue(); queue.Dequeue();
yield return queue.ToArray(); yield return [.. queue];
} }
} }
} }
+7 -7
View File
@@ -30,13 +30,13 @@ public class Day02 : IPuzzleSolver<long>
private static int GetTravelDistance(char waypoint, char[] program) private static int GetTravelDistance(char waypoint, char[] program)
{ {
var distance = 0; return program
foreach (var nextWaypoint in program) .Prepend(waypoint)
{ .SlidingWindow(2)
distance += GetDistance(waypoint, nextWaypoint); .Aggregate(0, (acc, next) =>
waypoint = nextWaypoint; next.Length < 2
} ? acc
return distance; : acc + GetDistance(next[0], next[1]));
} }
private static int GetDistance(char current, char next) private static int GetDistance(char current, char next)