This commit is contained in:
Aelita4 2022-12-09 21:39:00 +01:00
parent 22b16768f3
commit 7d835cdadf
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
1 changed files with 29 additions and 14 deletions

View File

@ -8,9 +8,21 @@ function isTailAdjacentToHead(head, tail) {
return true;
}
const head = { x: 0, y: 0}, tail = { x: 0, y: 0 };
const initX = 11, initY = 5;
const rope = [
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY },
{ x: initX, y: initY }
];
const visited = new Map([[ `0:0`, true ]]);
const visited = new Map();
input.split('\n').forEach(line => {
const operations = line.split(' ');
@ -33,19 +45,22 @@ input.split('\n').forEach(line => {
}
for(let i = 0; i < parseInt(operations[1]); i++) {
const oldHead = {};
oldHead.x = head.x;
oldHead.y = head.y;
rope[0].x += x;
rope[0].y += y;
head.x += x;
head.y += y;
if(!isTailAdjacentToHead(head, tail)) {
tail.x = oldHead.x;
tail.y = oldHead.y;
visited.set(`${tail.x}:${tail.y}`, true);
for(let ropeIndex = 1; ropeIndex < rope.length; ropeIndex++) {
if(!isTailAdjacentToHead(rope[ropeIndex - 1], rope[ropeIndex])) {
if(rope[ropeIndex - 1].x !== rope[ropeIndex].x && rope[ropeIndex - 1].y !== rope[ropeIndex].y) {
rope[ropeIndex].x += (rope[ropeIndex - 1].x - rope[ropeIndex].x) > 0 ? 1 : -1;
rope[ropeIndex].y += (rope[ropeIndex - 1].y - rope[ropeIndex].y) > 0 ? 1 : -1;
} else if(rope[ropeIndex - 1].x === rope[ropeIndex].x) {
rope[ropeIndex].y += (rope[ropeIndex - 1].y - rope[ropeIndex].y) > 0 ? 1 : -1;
} else if(rope[ropeIndex - 1].y === rope[ropeIndex].y) {
rope[ropeIndex].x += (rope[ropeIndex - 1].x - rope[ropeIndex].x) > 0 ? 1 : -1;
}
}
}
visited.set(`${rope[rope.length - 1].x}:${rope[rope.length - 1].y}`, true);
}
});