Parser.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Text.RegularExpressions;
  2. namespace Day8;
  3. public partial class Parser
  4. {
  5. [GeneratedRegex(@"(\w+)\s*=\s*\((\w+)\s*,\s*(\w+)\)")]
  6. private partial Regex LineMatch();
  7. public MapData Parse(string inputFile)
  8. {
  9. using var reader = File.OpenText(inputFile);
  10. var instructions = reader.ReadLine()!;
  11. reader.ReadLine(); // discard empty line
  12. var nodeMap = new Dictionary<string, Node>();
  13. while (!reader.EndOfStream)
  14. {
  15. var line = reader.ReadLine()!;
  16. var match = LineMatch().Match(line);
  17. if (!match.Success)
  18. {
  19. throw new Exception($"Expected node declaration, but got: {line}");
  20. }
  21. var node = GetNode(nodeMap, match.Groups[1].Value);
  22. node.Left = GetNode(nodeMap, match.Groups[2].Value);
  23. node.Right = GetNode(nodeMap, match.Groups[3].Value);
  24. }
  25. if (!nodeMap.TryGetValue("AAA", out var start))
  26. {
  27. throw new Exception($"Cannot find start node");
  28. }
  29. return new MapData(instructions, nodeMap.Values.ToList());
  30. }
  31. private Node GetNode(Dictionary<string, Node> nodeMap, string nodeName)
  32. {
  33. if (nodeMap.TryGetValue(nodeName, out Node? value))
  34. {
  35. return value;
  36. }
  37. value = new Node(nodeName);
  38. nodeMap[nodeName] = value;
  39. return value;
  40. }
  41. }