Refactor 2026 Day06 connection grid construction

This commit is contained in:
Sebastian Lindemeier committed 2026-12-06 16:59:25 +01:00
1 parent ea7c2ef950
commit f66a188a0e
1 file changed
+23 -24
+23 -24
View File
@@ -1,4 +1,5 @@
using AdvenOfCode.Contracts; using System.Net.Http.Headers;
using AdvenOfCode.Contracts;
using AdventOfCode.Extensions; using AdventOfCode.Extensions;
namespace AoC_2026; namespace AoC_2026;
@@ -10,36 +11,34 @@ public class Day06 : IPuzzleSolver<string>
var puzzleInput = File.ReadAllLines(path) var puzzleInput = File.ReadAllLines(path)
.Where(l => !string.IsNullOrWhiteSpace(l)) .Where(l => !string.IsNullOrWhiteSpace(l))
.Select(l => l.Split('-', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) .Select(l => l.Split('-', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Select(conn => (conn[0], .SelectMany(conn => conn[1]
conn[1].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet())) .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToDictionary(); .Select(to => (from: conn[0], to))
);
AddMissingKeys(puzzleInput); var connectionsGrid = GetConnectionsGrid(puzzleInput);
AddAllVertices(puzzleInput); return connectionsGrid;
return puzzleInput;
} }
private static void AddAllVertices(Dictionary<string, HashSet<string>> puzzleInput) private static Dictionary<string, HashSet<string>> GetConnectionsGrid(IEnumerable<(string, string)> puzzleInput)
{ {
foreach (var (from, tos) in puzzleInput) var grid = new Dictionary<string, HashSet<string>>();
foreach (var (from, to) in puzzleInput)
{ {
foreach (var to in tos) AddOrUpdate(grid, from, [to]);
{ AddOrUpdate(grid, to, [from]);
puzzleInput[to].Add(from);
}
}
} }
private static void AddMissingKeys(Dictionary<string, HashSet<string>> puzzleInput) return grid;
{
var missing = puzzleInput
.SelectMany(kv => kv.Value.Where(v => !puzzleInput.ContainsKey(v)))
.ToArray();
foreach (var key in missing)
{
puzzleInput[key] = [];
} }
private static void AddOrUpdate<TKey, TValue>(Dictionary<TKey, HashSet<TValue>> dictionary, TKey key,
HashSet<TValue> value) where TKey : notnull
{
if(dictionary.TryGetValue(key, out var existing))
dictionary[key].UnionWith(value);
else
dictionary[key] = value;
} }
public string SolvePart1(string pathToPuzzleInput) public string SolvePart1(string pathToPuzzleInput)