MapData.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. namespace Day8;
  2. public class MapData
  3. {
  4. public string Instructions { get; }
  5. public IList<Node> Nodes { get; }
  6. public MapData(string instructions, IList<Node> nodes)
  7. {
  8. Instructions = instructions;
  9. Nodes = nodes;
  10. }
  11. public long Walk()
  12. {
  13. var current = Nodes.First(n => n.IsStart);
  14. var steps = 0L;
  15. while (!current.IsEnd)
  16. {
  17. current = Move(steps, current);
  18. steps++;
  19. }
  20. return steps;
  21. }
  22. public long[] MultiWalk()
  23. {
  24. var starts = Nodes.Where(n => n.Name.Last() == 'A').ToArray();
  25. var cycleLengths = new List<long>();
  26. foreach (var node in starts)
  27. {
  28. var current = node;
  29. var steps = 0;
  30. while (!current.IsEnd)
  31. {
  32. current = Move(steps, current);
  33. steps++;
  34. }
  35. cycleLengths.Add(steps);
  36. Console.WriteLine(string.Join(", ", cycleLengths));
  37. }
  38. return cycleLengths.ToArray();
  39. }
  40. private Node Move(long step, Node node)
  41. {
  42. if (step >= 10000000)
  43. {
  44. throw new Exception("Over TEN MILLION");
  45. }
  46. var instruction = Instructions[(int)(step % Instructions.Length)];
  47. if (instruction != 'L' && instruction != 'R')
  48. {
  49. throw new Exception($"Unknown instruction: {instruction} @ {step}");
  50. }
  51. return (instruction == 'L' ? node.Left : node.Right)
  52. ?? throw new Exception($"Ended in null after: {instruction} @ {step}");
  53. }
  54. }