using AdventOfCode.Core.Shared.Grid; namespace AdventOfCode.Core.Shared { public class Grid where T : Point { public List DataGrid { get; set; } = []; public long Columns => DataGrid.Max(n => n.X) + 1; public long Rows => DataGrid.Max(n => n.Y) + 1; public Grid() { } public Grid(T[] data) => DataGrid.AddRange(data); public Grid(IEnumerable data) : this(data.ToArray()) { } public IEnumerable GetRow(long rowNumber) => DataGrid.Where(n => n.X == rowNumber); public string GetRowAsString(long columnNumber) => string.Concat(DataGrid.Where(n => n.Y == columnNumber).OrderBy(n => n.X).Select(n => n.Value)); public IEnumerable GetColumn(long columnNumber) => DataGrid.Where(n => n.Y == columnNumber); public string GetColumnAsString(long rowNumber) => string.Concat(DataGrid.Where(n => n.X == rowNumber).OrderBy(n => n.Y).Select(n => n.Value)); public T? TryGetNode(long x, long y) => DataGrid.FirstOrDefault(n => n.X == x && n.Y == y); public T GetNode(long x, long y) => DataGrid.First(n => n.X == x && n.Y == y); public IEnumerable FindWithValue(char toFind) => DataGrid.Where(n => n.Value == toFind); public void UpdateNode(T node) { T gridNode = DataGrid.First(n => n.X == node.X && n.Y == node.Y); int nodeLocation = DataGrid.IndexOf(gridNode); DataGrid[nodeLocation] = node; } public IEnumerable GetNeighbors(T source, bool allowDiagonals = true) { IEnumerable neighbors = DataGrid.Where(target => Math.Abs(source.X - target.X) <= 1 && Math.Abs(source.Y - target.Y) <= 1); if (allowDiagonals) { return neighbors; } return neighbors.Where(target => (Math.Abs(source.X - target.X) <= 1 && source.Y == target.Y) || (source.X == target.X && Math.Abs(source.Y - target.Y) <= 1)); } public IEnumerable GetSection(long fromX, long fromY, long toX, long toY) { return DataGrid.Where(node => node.X >= fromX && node.X <= toX && node.Y >= fromY && node.Y <= toY); } } }