45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
|
type Node = { name: string, left: string, right: string };
|
||
|
|
||
|
const input = await Deno.readTextFile("input.txt");
|
||
|
|
||
|
const lines = input.split("\n").map(x => x.trim()).filter(x => x.length > 0);
|
||
|
const instructions = lines[0];
|
||
|
const nodes = lines.splice(1).map(x=> {
|
||
|
const m = /(\w+)\s*=\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/.exec(x);
|
||
|
if (!m){
|
||
|
throw new Error("Invalid line: " + x);
|
||
|
}
|
||
|
return {name: m[1], left: m[2], right: m[3]};
|
||
|
});
|
||
|
|
||
|
|
||
|
console.log(instructions, nodes);
|
||
|
|
||
|
const map = new Map<string, Node>();
|
||
|
for (const node of nodes){
|
||
|
map.set(node.name, node);
|
||
|
}
|
||
|
|
||
|
function stepInst(node: Node, instruction: string){
|
||
|
if (instruction === "R"){
|
||
|
return node.right
|
||
|
} else {
|
||
|
return node.left
|
||
|
}
|
||
|
}
|
||
|
|
||
|
let step = 0;
|
||
|
let current = map.get("AAA");
|
||
|
if (!current){
|
||
|
throw new Error("Invalid input");
|
||
|
}
|
||
|
while (current.name !== "ZZZ"){
|
||
|
const instruction_index = step % instructions.length;
|
||
|
const instruction = instructions[instruction_index];
|
||
|
|
||
|
//execute
|
||
|
const next = stepInst(current, instruction);
|
||
|
current = map.get(next)!;
|
||
|
step++;
|
||
|
}
|
||
|
console.log(step);
|