Parser.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Text.RegularExpressions;
  2. namespace Day19;
  3. public partial class Parser
  4. {
  5. [GeneratedRegex(@"^(\w+)\{(.*)\}")]
  6. private partial Regex RuleMatch();
  7. [GeneratedRegex(@"(\w)=(\d+)")]
  8. private partial Regex PartMatch();
  9. public Data Parse(string inputFile)
  10. {
  11. using var reader = File.OpenText(inputFile);
  12. var ruleMap = new Dictionary<string, Rule>();
  13. var parts = new List<Part>();
  14. while (!reader.EndOfStream)
  15. {
  16. var line = reader.ReadLine()!;
  17. if (string.IsNullOrWhiteSpace(line))
  18. {
  19. break;
  20. }
  21. var match = RuleMatch().Match(line);
  22. if (!match.Success)
  23. {
  24. throw new Exception($"Invalid rule line: {line}");
  25. }
  26. ruleMap[match.Groups[1].Value] = new Rule(match.Groups[2].Value);
  27. }
  28. while (!reader.EndOfStream)
  29. {
  30. var line = reader.ReadLine()!;
  31. var partDict = PartMatch().Matches(line).ToDictionary(m => m.Groups[1].Value, m => int.Parse(m.Groups[2].Value));
  32. parts.Add(new Part(partDict));
  33. }
  34. return new Data(ruleMap, parts);
  35. }
  36. }