using System.Text.RegularExpressions; namespace Day20; public partial class Parser { [GeneratedRegex(@"(broadcaster|([%&-])(\w+)) -> (.*)")] private partial Regex LineMatch(); public SignalProcessor Parse(string inputFile) { using var reader = File.OpenText(inputFile); var modules = new Dictionary(); while (!reader.EndOfStream) { var line = reader.ReadLine()!; var match = LineMatch().Match(line); if (!match.Success) { throw new Exception($"Unable to parse line {line}"); } Module? module; if (match.Groups[1].Value == "broadcaster") { module = new BroadcastModule("broadcaster"); modules["broadcaster"] = (module, GetOutputs(match)); } else { if (match.Groups[2].Value == "%") { module = new FlipFlopModule(match.Groups[3].Value); } else if (match.Groups[2].Value == "&") { module = new ConjunctionModule(match.Groups[3].Value); } else if (match.Groups[2].Value == "-") { module = new SinkModule(match.Groups[3].Value); } else { throw new Exception($"Unknown module type: {match.Groups[2].Value}"); } modules[match.Groups[3].Value] = (module, GetOutputs(match)); } } return new SignalProcessor(modules); } private static string[] GetOutputs(Match match) { return match.Groups[4].Value .Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) .ToArray(); } }