Advent of Code 2022 - Day 9: Rope Bridge Solution

Manipulate coordination

Part 1

Use

Set
to store unique coordinations visited by tail

Implementation

1const fs = require("fs")
2
3const readData = () => {
4 const data = fs
5 .readFileSync("./input", "utf-8")
6 .split(/\r?\n/)
7 .map(row => row.split(" "))
8
9 return data
10}
11
12const main = () => {
13 const data = readData()
14 const coordSet = new Set()
15 const ROPE_LENGTH = 2
16 const rope = Array.from({ length: ROPE_LENGTH }, _ => ({ x: 0, y: 0 }))
17
18 const dirDelta = {
19 U: { x: 0, y: -1 },
20 D: { x: 0, y: 1 },
21 L: { x: -1, y: 0 },
22 R: { x: 1, y: 0 },
23 }
24
25 for (const [dir, numberOfSteps] of data) {
26 let stepsLeft = +numberOfSteps
27 const [head, tail] = [rope[0], rope.slice(-1)[0]]
28
29 while (stepsLeft--) {
30 head.x += dirDelta[dir].x
31 head.y += dirDelta[dir].y
32
33 for (let i = 1; i < rope.length; i++) {
34 const [prev, curr] = [rope[i - 1], rope[i]]
35 const delta = {
36 x: prev.x - curr.x,
37 y: prev.y - curr.y,
38 }
39
40 if (Math.abs(delta.x) >= 2 || Math.abs(delta.y) >= 2) {
41 delta.x = delta.x === 0 ? 0 : delta.x > 0 ? 1 : -1
42 delta.y = delta.y === 0 ? 0 : delta.y > 0 ? 1 : -1
43
44 curr.x += delta.x
45 curr.y += delta.y
46 }
47 }
48
49 coordSet.add(`${tail.x} ${tail.y}`)
50 }
51 }
52
53 const res = coordSet.size
54
55 console.log(res)
56}
57
58main()

Part 2

Change

ROPE_LENGTH
to
10

Implementation

1// ...
2const ROPE_LENGTH = 10
3// ...

References

Original problem

Comments

Loading comments...

Tags

adventofcode

hash table

Next Post

Advent of Code 2022 - Day 10: Cathode-Ray Tube

Dec 10, 2022

A creative challenge

Previous Post

Advent of Code 2022 - Day 8: Treetop Tree House

Dec 8, 2022

Dealing with matrix, straight-forward

HoningJS

Search Posts