|
|
@@ -3,43 +3,65 @@
|
|
|
public class MapData
|
|
|
{
|
|
|
public string Instructions { get; }
|
|
|
- public Node Start { get; }
|
|
|
+ public IList<Node> Nodes { get; }
|
|
|
|
|
|
- public MapData(string instructions, Node start)
|
|
|
+ public MapData(string instructions, IList<Node> nodes)
|
|
|
{
|
|
|
Instructions = instructions;
|
|
|
- Start = start;
|
|
|
+ Nodes = nodes;
|
|
|
}
|
|
|
|
|
|
public long Walk()
|
|
|
{
|
|
|
- var current = Start;
|
|
|
+ var current = Nodes.First(n => n.IsStart);
|
|
|
var steps = 0L;
|
|
|
|
|
|
- while (current.Name != "ZZZ")
|
|
|
+ while (!current.IsEnd)
|
|
|
{
|
|
|
- if (steps >= 1000000)
|
|
|
- {
|
|
|
- throw new Exception("Over ONE MILLION");
|
|
|
- }
|
|
|
-
|
|
|
- var instruction = Instructions[(int)(steps % Instructions.Length)];
|
|
|
- if (instruction != 'L' && instruction != 'R')
|
|
|
- {
|
|
|
- throw new Exception($"Unknown instruction: {instruction} @ {steps}");
|
|
|
- }
|
|
|
-
|
|
|
- Console.WriteLine($"{current.Name} => {instruction}");
|
|
|
-
|
|
|
+ current = Move(steps, current);
|
|
|
steps++;
|
|
|
- current = instruction == 'L' ? current.Left : current.Right;
|
|
|
+ }
|
|
|
+
|
|
|
+ return steps;
|
|
|
+ }
|
|
|
+
|
|
|
+ public long[] MultiWalk()
|
|
|
+ {
|
|
|
+ var starts = Nodes.Where(n => n.Name.Last() == 'A').ToArray();
|
|
|
+ var cycleLengths = new List<long>();
|
|
|
+
|
|
|
+ foreach (var node in starts)
|
|
|
+ {
|
|
|
+ var current = node;
|
|
|
+ var steps = 0;
|
|
|
|
|
|
- if (current == null)
|
|
|
+ while (!current.IsEnd)
|
|
|
{
|
|
|
- throw new Exception($"Ended in null after: {instruction} @ {steps}");
|
|
|
+ current = Move(steps, current);
|
|
|
+ steps++;
|
|
|
}
|
|
|
+
|
|
|
+ cycleLengths.Add(steps);
|
|
|
+ Console.WriteLine(string.Join(", ", cycleLengths));
|
|
|
}
|
|
|
|
|
|
- return steps;
|
|
|
+ return cycleLengths.ToArray();
|
|
|
+ }
|
|
|
+
|
|
|
+ private Node Move(long step, Node node)
|
|
|
+ {
|
|
|
+ if (step >= 10000000)
|
|
|
+ {
|
|
|
+ throw new Exception("Over TEN MILLION");
|
|
|
+ }
|
|
|
+
|
|
|
+ var instruction = Instructions[(int)(step % Instructions.Length)];
|
|
|
+ if (instruction != 'L' && instruction != 'R')
|
|
|
+ {
|
|
|
+ throw new Exception($"Unknown instruction: {instruction} @ {step}");
|
|
|
+ }
|
|
|
+
|
|
|
+ return (instruction == 'L' ? node.Left : node.Right)
|
|
|
+ ?? throw new Exception($"Ended in null after: {instruction} @ {step}");
|
|
|
}
|
|
|
}
|