SchematicParser.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Text.RegularExpressions;
  2. namespace Day3;
  3. public partial class SchematicParser
  4. {
  5. [GeneratedRegex(@"\d+|[^\d.]+")]
  6. private partial Regex TokenExtractor();
  7. public int Width { get; private set; }
  8. public int Height { get; private set; }
  9. public IEnumerable<Token> Parse(string inputFile)
  10. {
  11. using var reader = File.OpenText(inputFile);
  12. var row = 0;
  13. while (!reader.EndOfStream)
  14. {
  15. var line = reader.ReadLine()!;
  16. if (Width == 0)
  17. {
  18. Width = line.Length;
  19. }
  20. foreach (Match match in TokenExtractor().Matches(line))
  21. {
  22. if (match.Value[0] >= '0' && match.Value[0] <= '9')
  23. {
  24. yield return new NumberToken(match.Index, row, match.Value);
  25. }
  26. else
  27. {
  28. if (match.Length > 1)
  29. {
  30. throw new Exception($"Unexpected symbol token: {match.Value}");
  31. }
  32. yield return new SymbolToken(match.Index, row, match.Value);
  33. }
  34. }
  35. row++;
  36. }
  37. Height = row;
  38. }
  39. }