| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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<GameSamples> 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<SampleSet>();
- foreach (var set in match.Groups[2].Value.Split(';', StringSplitOptions.TrimEntries))
- {
- var map = new Dictionary<string, int>();
- 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);
- }
- }
- }
|