Skip to content

Instantly share code, notes, and snippets.

@kevinleedrum
Created December 9, 2022 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinleedrum/1809ba13225dd73fe6db045c19ed9b61 to your computer and use it in GitHub Desktop.
Save kevinleedrum/1809ba13225dd73fe6db045c19ed9b61 to your computer and use it in GitHub Desktop.
Advent of Code 2022 - Day 9
const KNOT_COUNT = 10;
const knots = new Array(KNOT_COUNT).fill().map((_) => ({ x: 0, y: 0 }));
const tailPositions = new Set();
tailPositions.add("0,0");
const moves = INPUT.split(/\n/).map((move) => {
let [direction, distance] = move.split(" ");
distance = +distance;
return { direction, distance };
});
moves.forEach((move) => {
for (let i = 0; i < move.distance; i++) {
if (move.direction === "U") knots[0].y -= 1;
if (move.direction === "D") knots[0].y += 1;
if (move.direction === "L") knots[0].x -= 1;
if (move.direction === "R") knots[0].x += 1;
moveTail(0);
}
});
console.log("Tail positions:", tailPositions.size);
function moveTail(headIdx) {
const head = knots[headIdx];
const tail = knots[headIdx + 1];
const xDist = Math.abs(head.x - tail.x);
const yDist = Math.abs(head.y - tail.y);
if (xDist < 2 && yDist < 2) return;
if (xDist === 2) {
tail.x += head.x > tail.x ? 1 : -1;
tail.y > head.y ? (tail.y -= 1) : tail.y === head.y ? 0 : (tail.y += 1);
} else if (yDist === 2) {
tail.y += head.y > tail.y ? 1 : -1;
tail.x > head.x ? (tail.x -= 1) : tail.x === head.x ? 0 : (tail.x += 1);
}
if (headIdx === knots.length - 2) {
tailPositions.add(`${tail.x},${tail.y}`);
} else {
moveTail(headIdx + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment