GameParser.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Text.RegularExpressions;
  2. namespace Day2;
  3. public partial class GameParser
  4. {
  5. [GeneratedRegex(@"^Game (\d+):(.*)$")]
  6. private partial Regex GameMatcher();
  7. [GeneratedRegex(@"(\d+)\s+(\w+)")]
  8. private partial Regex ItemMatcher();
  9. public GameParser()
  10. {
  11. }
  12. public IEnumerable<GameSamples> Parse(string inputFile)
  13. {
  14. using var reader = File.OpenText(inputFile);
  15. while (!reader.EndOfStream)
  16. {
  17. var line = reader.ReadLine()!;
  18. var match = GameMatcher().Match(line);
  19. if (!match.Success)
  20. {
  21. throw new Exception($"Line not matching expected Game format: {line}");
  22. }
  23. var id = int.Parse(match.Groups[1].Value);
  24. var samples = new List<SampleSet>();
  25. foreach (var set in match.Groups[2].Value.Split(';', StringSplitOptions.TrimEntries))
  26. {
  27. var map = new Dictionary<string, int>();
  28. foreach (var item in set.Split(',', StringSplitOptions.TrimEntries))
  29. {
  30. var itemMatch = ItemMatcher().Match(item);
  31. if (!itemMatch.Success)
  32. {
  33. throw new Exception($"Item content is invalid: {item}");
  34. }
  35. map[itemMatch.Groups[2].Value.ToLower()] = int.Parse(itemMatch.Groups[1].Value);
  36. }
  37. samples.Add(new SampleSet(
  38. map.GetValueOrDefault("red"),
  39. map.GetValueOrDefault("green"),
  40. map.GetValueOrDefault("blue")));
  41. }
  42. yield return new GameSamples(id, samples);
  43. }
  44. }
  45. }