using System.Text.RegularExpressions; namespace Day8; public partial class Parser { [GeneratedRegex(@"(\w+)\s*=\s*\((\w+)\s*,\s*(\w+)\)")] private partial Regex LineMatch(); public MapData Parse(string inputFile) { using var reader = File.OpenText(inputFile); var instructions = reader.ReadLine()!; reader.ReadLine(); // discard empty line var nodeMap = new Dictionary(); while (!reader.EndOfStream) { 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, nodeMap.Values.ToList()); } private Node GetNode(Dictionary nodeMap, string nodeName) { if (nodeMap.TryGetValue(nodeName, out Node? value)) { return value; } value = new Node(nodeName); nodeMap[nodeName] = value; return value; } }