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 connected = new LinkedList(); 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 linkedList) { var node = linkedList.First; List directions = new List(); 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) { return false; } 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); return allIncreasing || allDecreasing; 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 }