-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpart_2.js
51 lines (37 loc) · 1.49 KB
/
part_2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import fs from "node:fs";
import path from "node:path";
import { performance } from "node:perf_hooks";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// ========================= //
// = Copyright (c) NullDev = //
// ========================= //
/* eslint-disable no-nested-ternary */
/* eslint-disable key-spacing */
const CONTENT_READ = String(fs.readFileSync(path.join(__dirname, "input.txt"))).split("\n");
const pStart = performance.now();
const rotate = ([dx, dy], degrees) => ({
0: [ dx, dy],
90: [-dy, dx],
180: [-dx, -dy],
270: [ dy, -dx],
}[(degrees + 360) % 360]);
const directions = CONTENT_READ.reduce((move, line) => {
const action = line.trim()[0];
const value = Number(line.trim().slice(1));
move.XWaypoint += action === "E" ? value : action === "W" ? -value : 0;
move.YWaypoint += action === "N" ? value : action === "S" ? -value : 0;
const [XWaypoint, YWaypoint] = rotate(
[move.XWaypoint, move.YWaypoint],
action === "L" ? value : action === "R" ? -value : 0,
);
move.XWaypoint = XWaypoint;
move.YWaypoint = YWaypoint;
move.x += action === "F" ? move.XWaypoint * value : 0;
move.y += action === "F" ? move.YWaypoint * value : 0;
return move;
}, { x: 0, y: 0, XWaypoint: 10, YWaypoint: 1 });
const res = Math.abs(directions.x) + Math.abs(directions.y);
const pEnd = performance.now();
console.log("MANHATTAN DISTANCE: " + res);
console.log(pEnd - pStart);