| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- using System.Text.RegularExpressions;
- namespace Day19;
- public partial class Parser
- {
- [GeneratedRegex(@"^(\w+)\{(.*)\}")]
- private partial Regex RuleMatch();
-
- [GeneratedRegex(@"(\w)=(\d+)")]
- private partial Regex PartMatch();
-
- public Data Parse(string inputFile)
- {
- using var reader = File.OpenText(inputFile);
- var ruleMap = new Dictionary<string, Rule>();
- var parts = new List<Part>();
-
- while (!reader.EndOfStream)
- {
- var line = reader.ReadLine()!;
- if (string.IsNullOrWhiteSpace(line))
- {
- break;
- }
- var match = RuleMatch().Match(line);
- if (!match.Success)
- {
- throw new Exception($"Invalid rule line: {line}");
- }
- ruleMap[match.Groups[1].Value] = new Rule(match.Groups[2].Value);
- }
-
- while (!reader.EndOfStream)
- {
- var line = reader.ReadLine()!;
- var partDict = PartMatch().Matches(line).ToDictionary(m => m.Groups[1].Value, m => int.Parse(m.Groups[2].Value));
- parts.Add(new Part(partDict));
- }
- return new Data(ruleMap, parts);
- }
- }
|