-
Notifications
You must be signed in to change notification settings - Fork 0
/
puzzle.js
60 lines (49 loc) · 1.48 KB
/
puzzle.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
const foldUp = (grid, idx) => {
let top = grid.slice(0, idx);
let bottom = grid.slice(idx + 1, grid.length).reverse();
return mergeArrs(top, bottom);
};
const foldLeft = (grid, idx) => {
let left = grid.map((row) => row.slice(0, idx));
let right = grid.map((row) => row.slice(idx + 1, row.length).reverse());
return mergeArrs(left, right);
};
let mergeArrs = (a, b) => {
for (let y = 0; y < a.length; y++) {
const row = a[y];
for (let x = 0; x < row.length; x++) {
if (a[y][x] === "#" || b[y][x] === "#") {
a[y][x] = "#";
}
}
}
return a;
};
const applyFold = (fold, grid) => {
if (fold[0] === "x") {
return foldLeft(grid, parseInt(fold[1]));
} else if (fold[0] === "y") {
return foldUp(grid, parseInt(fold[1]));
}
};
const output = (input) => {
let [points, folds] = input.split("\n\n");
points = points.split("\n");
points = points.map((point) =>
point.split(",").map((num) => parseInt(num, 10))
);
let xMax = Math.max(...points.map(([x]) => x));
let yMax = Math.max(...points.map(([_, y]) => y));
let row = new Array(xMax + 1).fill(".");
let cols = new Array(yMax + 1).fill(".");
let grid = cols.map(() => [...row]);
folds = folds.split("\n").map((fold) => fold.split(" ")[2].split("="));
points.forEach(([x, y]) => {
grid[y][x] = "#";
});
let output = applyFold(folds[0], grid);
return output
.flat()
.reduce((prev, cur) => (cur === "#" ? prev + 1 : prev), 0);
};
module.exports = output;