using System.Text.RegularExpressions; namespace Day2; public partial class GameParser { [GeneratedRegex(@"^Game (\d+):(.*)$")] private partial Regex GameMatcher(); [GeneratedRegex(@"(\d+)\s+(\w+)")] private partial Regex ItemMatcher(); public GameParser() { } public IEnumerable Parse(string inputFile) { using var reader = File.OpenText(inputFile); while (!reader.EndOfStream) { var line = reader.ReadLine()!; var match = GameMatcher().Match(line); if (!match.Success) { throw new Exception($"Line not matching expected Game format: {line}"); } var id = int.Parse(match.Groups[1].Value); var samples = new List(); foreach (var set in match.Groups[2].Value.Split(';', StringSplitOptions.TrimEntries)) { var map = new Dictionary(); foreach (var item in set.Split(',', StringSplitOptions.TrimEntries)) { var itemMatch = ItemMatcher().Match(item); if (!itemMatch.Success) { throw new Exception($"Item content is invalid: {item}"); } map[itemMatch.Groups[2].Value.ToLower()] = int.Parse(itemMatch.Groups[1].Value); } samples.Add(new SampleSet( map.GetValueOrDefault("red"), map.GetValueOrDefault("green"), map.GetValueOrDefault("blue"))); } yield return new GameSamples(id, samples); } } }