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; 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 => { input.split('\n').forEach(line => {
const operations = line.split(' '); const operations = line.split(' ');
@ -33,20 +45,23 @@ input.split('\n').forEach(line => {
} }
for(let i = 0; i < parseInt(operations[1]); i++) { for(let i = 0; i < parseInt(operations[1]); i++) {
const oldHead = {}; rope[0].x += x;
oldHead.x = head.x; rope[0].y += y;
oldHead.y = head.y;
head.x += x; for(let ropeIndex = 1; ropeIndex < rope.length; ropeIndex++) {
head.y += y; if(!isTailAdjacentToHead(rope[ropeIndex - 1], rope[ropeIndex])) {
if(rope[ropeIndex - 1].x !== rope[ropeIndex].x && rope[ropeIndex - 1].y !== rope[ropeIndex].y) {
if(!isTailAdjacentToHead(head, tail)) { rope[ropeIndex].x += (rope[ropeIndex - 1].x - rope[ropeIndex].x) > 0 ? 1 : -1;
tail.x = oldHead.x; rope[ropeIndex].y += (rope[ropeIndex - 1].y - rope[ropeIndex].y) > 0 ? 1 : -1;
tail.y = oldHead.y; } else if(rope[ropeIndex - 1].x === rope[ropeIndex].x) {
rope[ropeIndex].y += (rope[ropeIndex - 1].y - rope[ropeIndex].y) > 0 ? 1 : -1;
visited.set(`${tail.x}:${tail.y}`, true); } 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);
}
}); });
console.log(visited.size); console.log(visited.size);