Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const eol = require('os').EOL;
- const startTime = new Date().getTime();
- let part1 = part2 = 0;
- let moves = fs.readFileSync(__dirname + "/data.txt", 'utf8').split(eol).map(a => a.split(" "));
- const dirs = {
- R: [1, 0],
- L: [-1, 0],
- U: [0, -1],
- D: [0, 1],
- };
- function solve(ropeLength) {
- let tSet = new Set();
- let rope = new Array(ropeLength).fill().map(u => [0, 0]);
- moves.forEach(move => {
- let [direction, steps] = move;
- for (let i = 0; i < steps; i++) {
- rope[0] = [rope[0][0] + dirs[direction][0], rope[0][1] + dirs[direction][1]];
- for (let j = 1; j < ropeLength; j++) {
- let dx = rope[j - 1][0] - rope[j][0];
- let dy = rope[j - 1][1] - rope[j][1];
- if (Math.abs(dx) > 1 || Math.abs(dy) > 1) {
- rope[j][0] += Math.sign(dx);
- rope[j][1] += Math.sign(dy);
- }
- }
- tSet.add(rope[ropeLength - 1].join("-"));
- }
- });
- return tSet.size;
- }
- part1 = solve(2);
- part2 = solve(10);
- let time = new Date().getTime() - startTime;
- console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${time} ms`);
Advertisement
Add Comment
Please, Sign In to add comment