advent-of-code/2022/9/index.js

83 lines
1.7 KiB
JavaScript
Raw Normal View History

const fs = require('fs/promises');
const tailVisited = {'0-0': true};
let hx = 0;
let hy = 0;
let tx = 0;
let ty = 0;
let lastHead = [0,0];
const moveRope = (direction) => {
console.log("Moving ", direction);
lastHead = [hx, hy];
switch (direction) {
case "R":
hx += 1;
break;
case "L":
hx -= 1;
break;
case "U":
hy -= 1;
break;
case "D":
hy += 1;
break;
}
if(Math.max(Math.abs(hx - tx), Math.abs(hy - ty)) > 1) {
[tx, ty ] = lastHead;
console.log("Moving Tail to: ", tx, ", ", ty);
tailVisited[`${tx}-${ty}`] = true;
}
}
const printGraph = () => {
console.log("\n\n");
for(let y = -15; y <= 15; y++) {
const row = ["·", "·", "·", "·", "·",
"·", "·", "·", "·", "·",
"·", "·", "·", "·", "·",
"·", "·", "·", "·", "·",
"·", "·", "·", "·", "·",
"·", "·", "·", "·", "·", "·"].map((spot, i) => {
const x = i - 15;
let ch = "·";
if(!(y % 5) && !(x % 5)) {
ch = "▪";
}
if(y === 0 && x === 0) {
ch = "0";
}
if(y === ty && x === tx) {
ch = "T";
}
if(y === hy && x === hx) {
ch = "H";
}
return ch;
});
console.log(row.join(""));
}
console.log("\n\n");
};
(async () => {
const input = await fs.readFile("./input.txt", 'utf8');
const lines = input.split("\n").map(t => t.split(" "));
//printGraph();
for (const [direction, times] of lines) {
for(let i = 0; i < times; ++i) {
moveRope(direction);
//printGraph();
}
}
console.log(Object.values(tailVisited).length);
})();