-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.js
86 lines (74 loc) · 2.22 KB
/
day14.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
75
76
77
78
79
80
81
82
83
84
85
86
import read from "../readFile.js";
const input = await read(14);
const grid = input.split("\n").map(l => l.split(""));
const gridSize = grid.length;
function northSupport(grid) {
let rows = gridSize;
let sum = 0;
for (let row of grid) {
sum += row.filter(i => i === "O").length * rows;
rows--;
}
return sum;
}
function tilt(grid, direction) {
for (let end = gridSize - 1; end > 0; end--) {
let anyMovement = false;
for (let axis1 = 0; axis1 < end; axis1++) {
for (let axis2 = 0; axis2 < gridSize; axis2++) {
switch (direction) {
case "N":
if (grid[axis1 + 1][axis2] === "O" && grid[axis1][axis2] === ".") {
grid[axis1 + 1][axis2] = ".";
grid[axis1][axis2] = "O";
anyMovement = true;
}
break;
case "W":
if (grid[axis2][axis1 + 1] === "O" && grid[axis2][axis1] === ".") {
grid[axis2][axis1 + 1] = ".";
grid[axis2][axis1] = "O";
anyMovement = true;
}
break;
case "S":
if (grid[axis1 + 1][axis2] === "." && grid[axis1][axis2] === "O") {
grid[axis1 + 1][axis2] = "O";
grid[axis1][axis2] = ".";
anyMovement = true;
}
break;
case "E":
if (grid[axis2][axis1 + 1] === "." && grid[axis2][axis1] === "O") {
grid[axis2][axis1 + 1] = "O";
grid[axis2][axis1] = ".";
anyMovement = true;
}
}
}
}
if (!anyMovement) {
break;
}
}
}
tilt(grid, "N");
console.log(northSupport(grid));
const prevsSet = new Set();
const prevsList = [];
for (let i = 0; i < 1_000_000_000; i++) {
tilt(grid, "N");
tilt(grid, "W");
tilt(grid, "S");
tilt(grid, "E");
const currState = grid.map(l => l.join("")).join("\n");
if (prevsSet.has(currState)) {
const encountered = prevsList.findIndex(x => x === currState);
const index = encountered + ((999_999_999 - encountered) % (i - encountered));
console.log(northSupport(prevsList[index].split("\n").map(l => l.split(""))));
break;
} else {
prevsSet.add(currState);
prevsList.push(currState);
}
}