using AdventOfCode.Core.Shared; using AdventOfCode.Core.Shared.Grid; namespace AdventOfCode.Core { public class InputReader { private readonly string InputFileTemplate = "../../../../AdventOfCode.Solutions/{1}/Day {0:00}/day-{0:00}-input.txt"; private readonly string DebugInputFileTemplate = "../../../../AdventOfCode.Solutions/day-00-input.txt"; public bool IsDebug = false; private int Day { get; set; } private int Year { get; set; } private string InputFilePath => IsDebug ? DebugInputFileTemplate : string.Format(InputFileTemplate, Day, Year); public void SetInput(IChallange challange) { Day = challange.Day; Year = challange.Year; } public void SetInput(int day, int year) { Day = day; Year = year; } public async Task ReadAsString() => await File.ReadAllTextAsync(InputFilePath); public async IAsyncEnumerable ReadAsStringLine() { using StreamReader reader = new(InputFilePath); while (!reader.EndOfStream) { yield return (await reader.ReadLineAsync()) ?? string.Empty; } } public Task ReadAsArrayString() { return File.ReadAllLinesAsync(InputFilePath); } public async Task ReadAsVerticalArrayString() { var data = await File.ReadAllLinesAsync(InputFilePath); List result = []; for (int index = 0; index < data[0].Length; index++) { result.Add(string.Concat(data.Select(l => l.Skip(index).First()))); } return [.. result]; } public async IAsyncEnumerable ReadAsStringLine(T emptyLineIndicator) { using StreamReader reader = new(InputFilePath); while (!reader.EndOfStream) { string line = (await reader.ReadLineAsync()) ?? string.Empty; if (string.IsNullOrWhiteSpace(line)) yield return emptyLineIndicator; else yield return (T)Convert.ChangeType(line, typeof(T)); } } public async IAsyncEnumerable ReadLineAsLongArray(string seperator) { using StreamReader reader = new(InputFilePath); while (!reader.EndOfStream) { string line = (await reader.ReadLineAsync()) ?? string.Empty; if (string.IsNullOrWhiteSpace(line)) yield return []; else yield return line.Split(seperator).Select(long.Parse).ToArray(); } } public async Task> ReadToGrid() where T : Point, new() { Grid result = new(); int row = 0; await foreach(string line in ReadAsStringLine()) { // create the nodes from the lines result.DataGrid.AddRange(line.Select((c, i) => new T { X = i, Y = row, Value = c })); row++; } return result; } public async IAsyncEnumerable> ReadToGrids() where T : Node, new() { Grid result = new(); int row = 0; string[] data = await ReadAsArrayString(); foreach (string line in data) { if (string.IsNullOrWhiteSpace(line)) { yield return result; result = new Grid(); row = 0; continue; } // create the nodes from the lines result.DataGrid.AddRange(line.Select((c, i) => new T { X = i, Y = row, Value = c })); row++; } yield return result; yield break; } } }