| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- namespace Day8;
- public class MapData
- {
- public string Instructions { get; }
- public IList<Node> Nodes { get; }
- public MapData(string instructions, IList<Node> nodes)
- {
- Instructions = instructions;
- Nodes = nodes;
- }
- public long Walk()
- {
- var current = Nodes.First(n => n.IsStart);
- var steps = 0L;
- while (!current.IsEnd)
- {
- current = Move(steps, current);
- steps++;
- }
- 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;
-
- while (!current.IsEnd)
- {
- current = Move(steps, current);
- steps++;
- }
-
- cycleLengths.Add(steps);
- Console.WriteLine(string.Join(", ", cycleLengths));
- }
- 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}");
- }
- }
|