Browse Source

Add day 8 part ii solution - kinda

This finds the numbers needed to get the LCM, but doesn't actually find
the LCM for you. I'll see about adding that later.
ApisNecros 1 year ago
parent
commit
f51d01e92d
1 changed files with 59 additions and 0 deletions
  1. 59 0
      8/8_2.ts

+ 59 - 0
8/8_2.ts

@@ -0,0 +1,59 @@
+import { Inspect, LoadInput } from "../common.ts";
+import { ParseMap, GetNextNodeInMap, type MapNodeTree } from "./8_common.ts";
+
+const tests = [
+    "LR",
+    "",
+    "11A = (11B, XXX)",
+    "11B = (XXX, 11Z)",
+    "11Z = (11B, XXX)",
+    "22A = (22B, XXX)",
+    "22B = (22C, 22C)",
+    "22C = (22Z, 22Z)",
+    "22Z = (22B, 22B)",
+    "XXX = (XXX, XXX)",
+];
+
+const input = await LoadInput(8);
+
+const [directions, map] = ParseMap(input);
+
+// Get a list of all node ID's starting with A
+let nodeList: Array<keyof MapNodeTree|undefined> = Object.keys(map).filter((nodeID) => nodeID[2] == "A");
+let cycleLengths = [...nodeList.keys()].fill(0, 0, nodeList.length);
+/** The total amount of steps taken */
+let stepsTaken = 0;
+
+do {
+    for (let i = 0; i < nodeList.length; i++) {
+        const currNodeID: keyof MapNodeTree|undefined = nodeList[i];
+        let nextNodeID: keyof MapNodeTree|undefined;
+        if (currNodeID) {
+            nextNodeID = GetNextNodeInMap(directions, map, currNodeID, stepsTaken);
+            
+            if (typeof nextNodeID == "string") {
+                nodeList[i] = nextNodeID;
+
+                if (nextNodeID[2] == "Z") {
+                    if (cycleLengths[i] == 0) {
+                        cycleLengths[i] = stepsTaken;
+                    }
+                    else {
+                        nodeList[i] = undefined;
+                        cycleLengths[i] = stepsTaken - cycleLengths[i];
+                        console.log(`Index ${i} has a cycle length of ${stepsTaken}`);
+                    }
+                }
+            }
+            else {
+                throw new Error(`Ran into an empty node after ${stepsTaken} steps`);
+            }
+        }
+    }
+    stepsTaken++;
+} while (nodeList.filter((n) => !!n).length);
+
+// TODO -- Add LCM finder
+
+console.log(`You'll need to now find the Least Common Multiple for the following values`);
+console.log(cycleLengths);