Files
adventofcode2024/Day2/Program.cs
2024-12-03 20:38:35 +01:00

85 lines
2.5 KiB
C#

string[] lines = """
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
""".Split('\n', StringSplitOptions.RemoveEmptyEntries);
// string[] lines = System.IO.File.ReadAllLines("input.txt");
int levelsSafe = 0;
foreach (string input in lines)
{
LinkedList<int> connected = new LinkedList<int>();
var levels = input.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
foreach (var paredLevel in levels)
{
connected.AddLast(paredLevel);
}
Console.Write($"Testing {input} = ");
var safe = TestLevel(connected);
Console.WriteLine($"{(safe ? "Safe" : "Unsafe")}");
levelsSafe += safe ? 1 : 0;
}
Console.WriteLine(levelsSafe);
bool TestLevel(LinkedList<int> linkedList)
{
int unsafeCount = 0;
var node = linkedList.First;
List<LevelDirection> directions = new List<LevelDirection>();
while (node != null)
{
bool safeRange = node switch
{
{ Previous: not null, Next: not null }
=> InsideRange2(node.Previous.Value, node.Value, node.Next.Value),
{ Previous: not null, Next: null }
=> InsideRange(node.Previous.Value, node.Value),
{ Previous: null, Next: not null }
=> InsideRange(node.Next.Value, node.Value),
_ => throw new InvalidOperationException()
};
if(safeRange is false)
{
unsafeCount++;
}
if (node.Next is not null)
{
directions.Add(node.Value > node.Next.Value ? LevelDirection.Increasing : LevelDirection.Decreasing);
}
node = node.Next;
}
bool allIncreasing = directions.All(x => x == LevelDirection.Increasing);
bool allDecreasing = directions.All(x => x == LevelDirection.Decreasing);
Console.Write($" {unsafeCount}|{allIncreasing}|{allDecreasing} ");
return ((allIncreasing || allDecreasing) && unsafeCount == 0) || (allIncreasing == false && allDecreasing == false);
bool InsideRange(int current, int target)
{
var abs = Math.Abs(current - target);
return abs is >= 1 and <= 3;
}
bool InsideRange2(int prev, int current, int next)
{
var p = Math.Abs(prev - current);
var n = Math.Abs(next - current);
return p is >= 1 and <= 3 && n is >= 1 and <= 3;
}
}
enum LevelDirection
{
Increasing,
Decreasing
}