| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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<string, Node>();
-
- 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<string, Node> nodeMap, string nodeName)
- {
- if (nodeMap.TryGetValue(nodeName, out Node? value))
- {
- return value;
- }
- value = new Node(nodeName);
- nodeMap[nodeName] = value;
- return value;
- }
- }
|