AdventOfCode/Advent Of Code Library/2022/Day 08/Day08Part2.cs
2022-12-11 15:25:13 +01:00

57 lines
2.7 KiB
C#

namespace AdventOfCodeLibrary._2022
{
using AdventOfCodeLibrary.Shared;
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();
}
}
}