this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

no bueno

+47 -15
+46 -14
2023/day08/part2.ts
··· 1 1 type Node = { L: string; R: string }; 2 + 2 3 type Network = Record<string, Node>; 3 4 5 + type Path = { 6 + possiblePaths: string[]; 7 + }; 8 + 9 + // 10 + 4 11 export function answer(input: string) { 5 12 const [instructions, , ...networkRaw] = input.split("\n"); 6 13 7 - const network: Network = networkRaw.reduce((network, line) => { 8 - const [id, leftAndRight] = line.split(" = "); 9 - const [L, R] = leftAndRight.replaceAll(/[\(\)]/g, "").split(", "); 10 - return { ...network, [id]: { L, R } }; 11 - }, {}); 14 + const parseNetwork = (lines: string[]): Network => 15 + lines.reduce((network, line) => { 16 + const [id, leftAndRight] = line.split(" = "); 17 + const [L, R] = leftAndRight.replaceAll(/[\(\)]/g, "").split(", "); 18 + return { ...network, [id]: { L, R } }; 19 + }, {}); 12 20 13 - const paths = Object.keys(network).filter((n) => n.endsWith("A")); 14 - return BigInt( 15 - paths 16 - .map((p) => countSteps(p, network, instructions)) 17 - .reduce((total, x) => (total *= x), 1), 18 - ); 21 + const network: Network = parseNetwork(networkRaw); 22 + 23 + // build the paths to X for each starting path 24 + // step forward by longest path 25 + // new positions are stepSize % pathSize 26 + 27 + const paths = Object.keys(network) 28 + .filter((n) => n.endsWith("A")) 29 + .map((p) => { 30 + const path = buildPath(p, network, instructions); 31 + console.log(`plength: ${path.length}, last: ${path[path.length - 1]}`); 32 + return { current: path.length - 1, path }; 33 + }); 34 + 35 + const stepSize = Math.max(...paths.map(({ path }) => path.length)); 36 + let stepTotal = stepSize; 37 + 38 + while (!paths.every((p) => p.path[p.current] === "Z")) { 39 + console.log(`step by ${stepSize}`); 40 + paths.forEach((p) => { 41 + p.current += stepSize; 42 + p.current = p.path.length % p.current; 43 + console.log(p); 44 + }); 45 + stepTotal += stepSize; 46 + } 47 + 48 + return stepTotal; 19 49 } 20 50 21 - function countSteps( 51 + function buildPath( 22 52 start: string, 23 53 network: Network, 24 54 instructions: string, 25 - ): number { 55 + ): string[] { 26 56 let currentNode = start; 27 57 let stepCount = 0; 58 + const endingChars = [start[2]]; 28 59 while (!currentNode.endsWith("Z")) { 29 60 for (const dir of instructions.split("")) { 30 61 currentNode = network[currentNode][dir as keyof Node]; 31 62 stepCount++; 63 + endingChars.push(currentNode[2]); 32 64 if (currentNode.endsWith("Z")) break; 33 65 } 34 66 } 35 67 36 - return stepCount; 68 + return endingChars; 37 69 } 38 70 39 71 if (import.meta.main) {
+1 -1
2023/day08/test.ts
··· 41 41 "22Z = (22B, 22B)", 42 42 "XXX = (XXX, XXX)", 43 43 ].join("\n"); 44 - assertEquals(p2.answer(examples), BigInt(6)); 44 + assertEquals(p2.answer(examples), 6); 45 45 });