55 lines
2.7 KiB
C#
55 lines
2.7 KiB
C#
namespace AdventOfCode.Solutions._2022
|
|
{
|
|
public class Day08Part2 : Answerable
|
|
{
|
|
public override int Year { get; set; } = 2022;
|
|
public override int Day { get; set; } = 8;
|
|
public override int Part { get; set; } = 2;
|
|
|
|
public override string GetAnswer(byte[] data)
|
|
{
|
|
string[] treeGrid = GetAsStringArray(data);
|
|
|
|
int highestScenicScore = 0;
|
|
for (int row = 0; row < treeGrid.Length; row++)
|
|
{
|
|
for (int col = 0; col < treeGrid[row].Length; col++)
|
|
{
|
|
if (row == 0 || col == 0 || row == treeGrid.Length - 1 || col == treeGrid[row].Length - 1)
|
|
{
|
|
// skip the edges
|
|
continue;
|
|
}
|
|
|
|
// get the height of the current tree
|
|
char treeHeight = treeGrid[row][col];
|
|
|
|
List<char> leftTrees = treeGrid[row].Take(col).ToList();
|
|
int firstLeftBlockingTreeIdx = leftTrees.FindLastIndex(height => height >= treeHeight);
|
|
int viewCountFromLeft = firstLeftBlockingTreeIdx == -1 ? leftTrees.Count : col - firstLeftBlockingTreeIdx;
|
|
|
|
List<char> rightTrees = treeGrid[row].Skip(col + 1).Take(treeGrid[row].Length - col - 1).Reverse().ToList();
|
|
int firstRightBlockingTreeIdx = rightTrees.FindLastIndex(height => height >= treeHeight);
|
|
int viewCountFromRight = firstRightBlockingTreeIdx == -1 ? rightTrees.Count : treeGrid[row].Length - col - firstRightBlockingTreeIdx - 1;
|
|
|
|
List<char> topTrees = treeGrid.Skip(0).Take(row).Select(ints => ints[col]).ToList();
|
|
int firstTopBlockingTreeIdx = topTrees.FindLastIndex(height => height >= treeHeight);
|
|
int viewCountFromTop = firstTopBlockingTreeIdx == -1 ? topTrees.Count : row - firstTopBlockingTreeIdx;
|
|
|
|
List<char> bottomTrees = treeGrid.Skip(row + 1).Take(treeGrid.Length - row - 1).Select(ints => ints[col]).Reverse().ToList();
|
|
int firstBottomBlockingTreeIdx = bottomTrees.FindLastIndex(height => height >= treeHeight);
|
|
int viewCountFromBottom = firstBottomBlockingTreeIdx == -1 ? bottomTrees.Count : treeGrid.Length - row - firstBottomBlockingTreeIdx - 1;
|
|
|
|
int scenicScore = viewCountFromLeft * viewCountFromRight * viewCountFromTop * viewCountFromBottom;
|
|
if (scenicScore > highestScenicScore)
|
|
{
|
|
highestScenicScore = scenicScore;
|
|
}
|
|
}
|
|
}
|
|
|
|
return highestScenicScore.ToString();
|
|
}
|
|
}
|
|
}
|