AdventOfCode/Advent Of Code Library/2022/Day 08/TreeChecker.cs
2022-12-08 13:20:39 +01:00

74 lines
2.8 KiB
C#

namespace AdventOfCodeLibrary._2022.Day_08
{
internal class TreeChecker
{
internal int VisibleTrees(string[] treeArray)
{
int visible = 0;
// start from the top
char[] currentHighest = treeArray[0].ToCharArray();
// from top to bottom
for (int treeIndex = 1; treeIndex < treeArray.Length - 2; treeIndex++)
{
visible += CheckVisibleTrees(ref currentHighest, treeArray[treeIndex].ToCharArray());
}
currentHighest = treeArray[^1].ToCharArray();
// from bottom to top
for (int treeIndex = treeArray.Length - 1; treeIndex > 1 ; treeIndex--)
{
visible += CheckVisibleTrees(ref currentHighest, treeArray[treeIndex].ToCharArray());
}
string[] rotatedTreeArray = new string[treeArray[0].Length];
// parse the array so we get array 90 rotated
for (int horizontalIndex = 0; horizontalIndex < treeArray[0].Length; horizontalIndex++)
{
for (int verticalIndex = 0; verticalIndex < treeArray.Length; verticalIndex++)
{
rotatedTreeArray[horizontalIndex] += treeArray[verticalIndex][horizontalIndex];
}
}
currentHighest = rotatedTreeArray[0].ToCharArray();
// from top to bottom with the rotated array
for (int treeIndex = 1; treeIndex < rotatedTreeArray.Length - 1; treeIndex++)
{
visible += CheckVisibleTrees(ref currentHighest, rotatedTreeArray[treeIndex].ToCharArray());
}
currentHighest = rotatedTreeArray[^1].ToCharArray();
// from bottom to top with the rotated array
for (int treeIndex = rotatedTreeArray.Length - 1; treeIndex > 1; treeIndex--)
{
visible += CheckVisibleTrees(ref currentHighest, rotatedTreeArray[treeIndex].ToCharArray());
}
// add the outside trees
int edgeTrees = (2 * treeArray.Length) + (2 * (treeArray[0].Length - 2));
// return the result
return visible + edgeTrees;
}
private int CheckVisibleTrees(ref char[] currentHighest, char[] treeLineToCheck)
{
int visible = 0;
for (int treeIndex = 1; treeIndex < treeLineToCheck.Length - 1; treeIndex++)
{
int diff = treeLineToCheck[treeIndex] - currentHighest[treeIndex];
if (diff > 0)
{
visible++;
currentHighest[treeIndex] = treeLineToCheck[treeIndex];
}
}
return visible;
}
}
}