8_2.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { Inspect, LoadInput } from "../common.ts";
  2. import { ParseMap, GetNextNodeInMap, type MapNodeTree } from "./8_common.ts";
  3. const tests = [
  4. "LR",
  5. "",
  6. "11A = (11B, XXX)",
  7. "11B = (XXX, 11Z)",
  8. "11Z = (11B, XXX)",
  9. "22A = (22B, XXX)",
  10. "22B = (22C, 22C)",
  11. "22C = (22Z, 22Z)",
  12. "22Z = (22B, 22B)",
  13. "XXX = (XXX, XXX)",
  14. ];
  15. const input = await LoadInput(8);
  16. const [directions, map] = ParseMap(input);
  17. // Get a list of all node ID's starting with A
  18. let nodeList: Array<keyof MapNodeTree|undefined> = Object.keys(map).filter((nodeID) => nodeID[2] == "A");
  19. let cycleLengths = [...nodeList.keys()].fill(0, 0, nodeList.length);
  20. /** The total amount of steps taken */
  21. let stepsTaken = 0;
  22. do {
  23. for (let i = 0; i < nodeList.length; i++) {
  24. const currNodeID: keyof MapNodeTree|undefined = nodeList[i];
  25. let nextNodeID: keyof MapNodeTree|undefined;
  26. if (currNodeID) {
  27. nextNodeID = GetNextNodeInMap(directions, map, currNodeID, stepsTaken);
  28. if (typeof nextNodeID == "string") {
  29. nodeList[i] = nextNodeID;
  30. if (nextNodeID[2] == "Z") {
  31. if (cycleLengths[i] == 0) {
  32. cycleLengths[i] = stepsTaken;
  33. }
  34. else {
  35. nodeList[i] = undefined;
  36. cycleLengths[i] = stepsTaken - cycleLengths[i];
  37. console.log(`Index ${i} has a cycle length of ${stepsTaken}`);
  38. }
  39. }
  40. }
  41. else {
  42. throw new Error(`Ran into an empty node after ${stepsTaken} steps`);
  43. }
  44. }
  45. }
  46. stepsTaken++;
  47. } while (nodeList.filter((n) => !!n).length);
  48. // TODO -- Add LCM finder
  49. console.log(`You'll need to now find the Least Common Multiple for the following values`);
  50. console.log(cycleLengths);