|
@@ -4,16 +4,50 @@ namespace Day8;
|
|
|
|
|
|
|
|
public partial class Parser
|
|
public partial class Parser
|
|
|
{
|
|
{
|
|
|
- [GeneratedRegex(@".*")]
|
|
|
|
|
|
|
+ [GeneratedRegex(@"(\w+)\s*=\s*\((\w+)\s*,\s*(\w+)\)")]
|
|
|
private partial Regex LineMatch();
|
|
private partial Regex LineMatch();
|
|
|
|
|
|
|
|
- public void Parse(string inputFile)
|
|
|
|
|
|
|
+ public MapData Parse(string inputFile)
|
|
|
{
|
|
{
|
|
|
using var reader = File.OpenText(inputFile);
|
|
using var reader = File.OpenText(inputFile);
|
|
|
|
|
|
|
|
|
|
+ var instructions = reader.ReadLine()!;
|
|
|
|
|
+ reader.ReadLine(); // discard empty line
|
|
|
|
|
+
|
|
|
|
|
+ var nodeMap = new Dictionary<string, Node>();
|
|
|
|
|
+
|
|
|
while (!reader.EndOfStream)
|
|
while (!reader.EndOfStream)
|
|
|
{
|
|
{
|
|
|
var line = reader.ReadLine()!;
|
|
var line = reader.ReadLine()!;
|
|
|
|
|
+ var match = LineMatch().Match(line);
|
|
|
|
|
+ if (!match.Success)
|
|
|
|
|
+ {
|
|
|
|
|
+ throw new Exception($"Expected node declaration, but got: {line}");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ var node = GetNode(nodeMap, match.Groups[1].Value);
|
|
|
|
|
+ node.Left = GetNode(nodeMap, match.Groups[2].Value);
|
|
|
|
|
+ node.Right = GetNode(nodeMap, match.Groups[3].Value);
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ if (!nodeMap.TryGetValue("AAA", out var start))
|
|
|
|
|
+ {
|
|
|
|
|
+ throw new Exception($"Cannot find start node");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return new MapData(instructions, start);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private Node GetNode(Dictionary<string, Node> nodeMap, string nodeName)
|
|
|
|
|
+ {
|
|
|
|
|
+ if (nodeMap.TryGetValue(nodeName, out Node? value))
|
|
|
|
|
+ {
|
|
|
|
|
+ return value;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ value = new Node(nodeName);
|
|
|
|
|
+ nodeMap[nodeName] = value;
|
|
|
|
|
+
|
|
|
|
|
+ return value;
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|