AdventOfCode/AdventOfCode.Solutions/2023/Day 13/Day13.cs

94 lines
3.0 KiB
C#

using AdventOfCode.Core;
using AdventOfCode.Solutions._2023.Day_13;
using System.Data;
namespace AdventOfCode.Solutions._2023
{
public class Day13(InputReader reader) : IChallange
{
private InputReader _inputReader = reader;
public async Task<string> GetSolutionPart1()
{
int rowMirrors = 0, columnMirrors = 0;
await foreach (Grid<Node> map in _inputReader.ReadToGrids<Node>())
{
(List<string> rows, List<string> columns) = map.GetRowsAndColumns();
int r = 0, c = 0;
r = GetReflectedRow(rows, false);
rowMirrors += r;
if (r == 0)
{
c = GetReflectedRow(columns, false);
columnMirrors += c;
}
}
return (rowMirrors * 100 + columnMirrors).ToString();
}
public async Task<string> GetSolutionPart2()
{
int rowMirrors = 0, columnMirrors = 0;
await foreach (Grid<Node> map in _inputReader.ReadToGrids<Node>())
{
(List<string> rows, List<string> columns) = map.GetRowsAndColumns();
int r = 0, c = 0;
r = GetReflectedRow(rows, true);
rowMirrors += r;
if (r == 0)
{
c = GetReflectedRow(columns, true);
columnMirrors += c;
}
}
return (rowMirrors * 100 + columnMirrors).ToString();
}
private static int GetReflectedRow(List<string> lines, bool derectSmudge = false)
{
for (var rowIndex = 0; rowIndex < lines.Count - 1; rowIndex++)
{
bool foundMirrors = false, foundSmudge = false;
for (var charIndex = 0; charIndex < lines[rowIndex].Length; charIndex++)
{
for (var smudge = 0; smudge <= Math.Min(rowIndex, lines.Count - 2 - rowIndex); smudge++)
{
if (lines[rowIndex - smudge][charIndex] != lines[rowIndex + 1 + smudge][charIndex])
{
if (derectSmudge && !foundSmudge)
{
foundSmudge = true;
}
else
{
foundMirrors = true;
break;
}
}
}
if (foundMirrors)
{
break;
}
}
if (derectSmudge && !foundSmudge)
{
// continue to find the damn thing
continue;
}
if (!foundMirrors)
{
return rowIndex + 1;
}
}
return 0;
}
}
}