| 1234567891011121314151617181920212223242526272829303132333435 |
- using System.Text.RegularExpressions;
- namespace Day1;
- public class CalibrationExtractor
- {
- private readonly string _fileName;
- private readonly DigitTransformer _transformer;
- private readonly Regex _nonDigit = new Regex(@"[^\d]", RegexOptions.Compiled);
- public CalibrationExtractor(string fileName, DigitTransformer transformer = null)
- {
- _fileName = fileName;
- _transformer = transformer;
- }
- public IEnumerable<int> Extract()
- {
- using var reader = File.OpenText(_fileName);
- while (!reader.EndOfStream)
- {
- var line = reader.ReadLine();
- if (_transformer != null)
- {
- line = _transformer.Replace(line);
- }
- var calibrationValueStr = _nonDigit.Replace(line, "");
- if (calibrationValueStr.Length < 1)
- {
- throw new InvalidOperationException($"Not enough digits: '{line}'");
- }
- yield return int.Parse(new string(new char[] { calibrationValueStr.First(), calibrationValueStr.Last() }));
- }
- }
- }
|