mosredna

AoC 2022 day 9

Dec 9th, 2022 (edited)
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.22 KB | Source Code | 0 0
  1. const fs = require('fs');
  2. const eol = require('os').EOL;
  3.  
  4. const startTime = new Date().getTime();
  5. let part1 = part2 = 0;
  6. let moves = fs.readFileSync(__dirname + "/data.txt", 'utf8').split(eol).map(a => a.split(" "));
  7.  
  8. const dirs = {
  9.     R: [1, 0],
  10.     L: [-1, 0],
  11.     U: [0, -1],
  12.     D: [0, 1],
  13. };
  14.  
  15. function solve(ropeLength) {
  16.     let tSet = new Set();
  17.     let rope = new Array(ropeLength).fill().map(u => [0, 0]);
  18.     moves.forEach(move => {
  19.         let [direction, steps] = move;
  20.         for (let i = 0; i < steps; i++) {
  21.             rope[0] = [rope[0][0] + dirs[direction][0], rope[0][1] + dirs[direction][1]];
  22.             for (let j = 1; j < ropeLength; j++) {
  23.                 let dx = rope[j - 1][0] - rope[j][0];
  24.                 let dy = rope[j - 1][1] - rope[j][1];
  25.                 if (Math.abs(dx) > 1 || Math.abs(dy) > 1) {
  26.                     rope[j][0] += Math.sign(dx);
  27.                     rope[j][1] += Math.sign(dy);
  28.                 }
  29.             }
  30.             tSet.add(rope[ropeLength - 1].join("-"));
  31.         }
  32.     });
  33.     return tSet.size;
  34. }
  35. part1 = solve(2);
  36. part2 = solve(10);
  37. let time = new Date().getTime() - startTime;
  38. console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${time} ms`);
Advertisement
Add Comment
Please, Sign In to add comment