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;
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
if(dictionary.TryGetValue(key, out var existing))
|
||||||
.SelectMany(kv => kv.Value.Where(v => !puzzleInput.ContainsKey(v)))
|
dictionary[key].UnionWith(value);
|
||||||
.ToArray();
|
else
|
||||||
foreach (var key in missing)
|
dictionary[key] = value;
|
||||||
{
|
|
||||||
puzzleInput[key] = [];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public string SolvePart1(string pathToPuzzleInput)
|
public string SolvePart1(string pathToPuzzleInput)
|
||||||
|
|||||||
Reference in new issue
Block a user