AdventOfCode/AdventOfCode.Core/Shared/Grid.cs
2024-12-04 13:28:55 +01:00

53 lines
2.2 KiB
C#

using AdventOfCode.Core.Shared.Grid;
namespace AdventOfCode.Core.Shared
{
public class Grid<T> where T : Point
{
public List<T> 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<T> data) : this(data.ToArray()) { }
public IEnumerable<T> 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<T> 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<T> 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<T> GetNeighbors(T source, bool allowDiagonals = true)
{
IEnumerable <T> 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<T> 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);
}
}
}