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