From 7d835cdadf7d9f71f4f2ff88c51b58e7a24488c0 Mon Sep 17 00:00:00 2001 From: Aelita4 Date: Fri, 9 Dec 2022 21:39:00 +0100 Subject: [PATCH] 09_2 --- day09/index.js | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/day09/index.js b/day09/index.js index 849b25f..5ab1999 100644 --- a/day09/index.js +++ b/day09/index.js @@ -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,20 +45,23 @@ 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); + } }); console.log(visited.size); \ No newline at end of file