Skip to content

Instantly share code, notes, and snippets.

@gianugo
Created Dec 9, 2021
Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
namespace Day9
{
class Program
{
static void Main(string[] args)
{
int[][] Map;
List<int[]> MapAsList = new List<int[]>();
foreach (String line in System.IO.File.ReadLines(@"c:\Temp\day9.txt"))
{
MapAsList.Add(Array.ConvertAll(line.ToCharArray(), x => (int)Char.GetNumericValue(x)));
}
Map = MapAsList.ToArray();
List<int> LowPoints = new List<int>();
int Y = 0;
List<int> Basins = new List<int>();
foreach (int[] Line in Map)
{
int X = 0;
foreach (int Candidate in Line)
{
if (IsLowPoint(Y, X, Map))
{
LowPoints.Add(Candidate + 1);
int Basin = CountNeighbors(Y, X, Map);
Basins.Add(Basin);
}
X++;
}
Y++;
}
Console.WriteLine("Part 1: " + LowPoints.Sum());
int[] top3 = Basins.OrderByDescending(x => x).Take(3).ToArray();
Console.WriteLine("Part 2: " + top3[0] * top3[1] * top3[2]);
}
static int CountNeighbors(int Y, int X, int[][] Map)
{
if (X < 0 || Y < 0)
{
return 0;
}
Map[Y][X] = 9;
int ret = 1;
// N
if (Y > 0 && Map[Y-1][X] != 9) {
ret = ret + CountNeighbors(Y - 1, X, Map);
}
// W
if (X > 0 && Map[Y][X-1] != 9)
{
ret = ret + CountNeighbors(Y, X - 1, Map);
}
// E
if (X < Map[Y].Length -1 && Map[Y][X + 1] != 9)
{
ret = ret + CountNeighbors(Y, X + 1, Map);
}
// S
if (Y < Map.Length - 1 && Map[Y + 1][X] != 9)
{
ret = ret + CountNeighbors(Y + 1, X, Map);
}
return ret;
}
static bool IsLowPoint(int Y, int X, int[][] Map)
{
List<int> TestNumbers = new List<int>();
// Top row
if (Y != 0)
{
if (X > 0)
{
TestNumbers.Add(Map[Y - 1][X - 1]);
}
TestNumbers.Add(Map[Y - 1][X]);
if (X < Map[Y -1].Length -1)
{
TestNumbers.Add(Map[Y - 1][X + 1]);
}
}
// Row
if (X > 0)
{
TestNumbers.Add(Map[Y][X - 1]);
}
if (X < Map[Y].Length - 1)
{
TestNumbers.Add(Map[Y][X + 1]);
}
// Bottom row
if (Y < Map.Length - 1)
{
if (X > 0)
{
TestNumbers.Add(Map[Y + 1][X - 1]);
}
TestNumbers.Add(Map[Y + 1][X]);
if (X < Map[Y].Length - 1)
{
TestNumbers.Add(Map[Y + 1][X + 1]);
}
}
foreach(int TestNumber in TestNumbers)
{
if (TestNumber <= Map[Y][X]) return false;
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment