-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
74 lines (58 loc) · 1.63 KB
/
part2.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString().trim();
const robots = [];
const GRID_WIDTH = 101;
const GRID_HEIGHT = 103;
input.split("\n").forEach((line) => {
const regex = /-?\d+/g;
const values = line.match(regex).map((x) => parseInt(x));
robots.push({
id: robots.length,
position: [values[0], values[1]],
velocity: [values[2], values[3]],
});
});
function displayGrid() {
const grid = Array.from({ length: GRID_HEIGHT }, () =>
Array(GRID_WIDTH).fill(0)
);
robots.forEach((robot) => {
grid[robot.position[1]][robot.position[0]]++;
});
grid.forEach((line) => {
console.log(line.map((x) => (x == 0 ? "." : x.toString())).join(""));
});
console.log("Elapsed Seconds", elapsedSeconds);
}
function computeVariations() {
let totalDistance = 0;
let coords = robots.map((r) => r.position);
for (let i = 1; i < coords.length; i++) {
const x1 = coords[i - 1][0];
const y1 = coords[i - 1][1];
const x2 = coords[i][0];
const y2 = coords[i][1];
totalDistance += Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
return totalDistance / (coords.length - 1);
}
function tick() {
robots.forEach((robot) => {
let x = (robot.position[0] + robot.velocity[0]) % GRID_WIDTH;
let y = (robot.position[1] + robot.velocity[1]) % GRID_HEIGHT;
if (x < 0) x = GRID_WIDTH + x;
if (y < 0) y = GRID_HEIGHT + y;
robot.position = [x, y];
});
}
let elapsedSeconds = 0;
while (true) {
tick();
elapsedSeconds++;
if (computeVariations() < 40) {
displayGrid();
break;
}
}