63 lines
1.5 KiB
TypeScript
63 lines
1.5 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 = nodes;
|
||
|
if (!current){
|
||
|
throw new Error("Invalid input");
|
||
|
}
|
||
|
|
||
|
const a = new Map<string, string[]>();
|
||
|
nodes.forEach(x => {
|
||
|
a.set(x.name, [x.name]);
|
||
|
});
|
||
|
|
||
|
// brute force
|
||
|
while (step < instructions.length){
|
||
|
const instruction_index = step % instructions.length;
|
||
|
const instruction = instructions[instruction_index];
|
||
|
|
||
|
//execute
|
||
|
current = current.map(x => {
|
||
|
const next = stepInst(x, instruction);
|
||
|
return map.get(next)!
|
||
|
});
|
||
|
nodes.forEach((x,i) => {
|
||
|
a.get(x.name)?.push(current[i].name);
|
||
|
})
|
||
|
step++;
|
||
|
}
|
||
|
await Deno.writeTextFile("s.json", JSON.stringify(current.map((x,i) => {
|
||
|
return {
|
||
|
prev: nodes[i].name,
|
||
|
name: x.name,
|
||
|
progress: a.get(x.name),
|
||
|
}
|
||
|
}), null, 2));
|