Refactor Day02 travel distance calculation to use SlidingWindow
This commit is contained in:
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -30,13 +30,13 @@ public class Day02 : IPuzzleSolver<long>
|
||||
|
||||
private static int GetTravelDistance(char waypoint, char[] program)
|
||||
{
|
||||
var distance = 0;
|
||||
foreach (var nextWaypoint in program)
|
||||
{
|
||||
distance += GetDistance(waypoint, nextWaypoint);
|
||||
waypoint = nextWaypoint;
|
||||
}
|
||||
return distance;
|
||||
return program
|
||||
.Prepend(waypoint)
|
||||
.SlidingWindow(2)
|
||||
.Aggregate(0, (acc, next) =>
|
||||
next.Length < 2
|
||||
? acc
|
||||
: acc + GetDistance(next[0], next[1]));
|
||||
}
|
||||
|
||||
private static int GetDistance(char current, char next)
|
||||
|
||||
Reference in new issue
Block a user