Advent of Code 2022 - Day 9: Rope Bridge Solution
Manipulate coordinationPart 1
Use Set
to store unique coordinations visited by tail
Implementation
1const fs = require("fs")23const readData = () => {4 const data = fs5 .readFileSync("./input", "utf-8")6 .split(/\r?\n/)7 .map(row => row.split(" "))89 return data10}1112const main = () => {13 const data = readData()14 const coordSet = new Set()15 const ROPE_LENGTH = 216 const rope = Array.from({ length: ROPE_LENGTH }, _ => ({ x: 0, y: 0 }))1718 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 }2425 for (const [dir, numberOfSteps] of data) {26 let stepsLeft = +numberOfSteps27 const [head, tail] = [rope[0], rope.slice(-1)[0]]2829 while (stepsLeft--) {30 head.x += dirDelta[dir].x31 head.y += dirDelta[dir].y3233 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 }3940 if (Math.abs(delta.x) >= 2 || Math.abs(delta.y) >= 2) {41 delta.x = delta.x === 0 ? 0 : delta.x > 0 ? 1 : -142 delta.y = delta.y === 0 ? 0 : delta.y > 0 ? 1 : -14344 curr.x += delta.x45 curr.y += delta.y46 }47 }4849 coordSet.add(`${tail.x} ${tail.y}`)50 }51 }5253 const res = coordSet.size5455 console.log(res)56}5758main()
Part 2
Change ROPE_LENGTH
to 10
Implementation
1// ...2const ROPE_LENGTH = 103// ...
References
Comments
Loading comments...
Tags
adventofcode
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Advent of Code 2022 - Day 10: Cathode-Ray Tube
A creative challenge
Previous Post
Advent of Code 2022 - Day 8: Treetop Tree House
Dealing with matrix, straight-forward