-
Notifications
You must be signed in to change notification settings - Fork 4
/
day13.js
84 lines (74 loc) · 2.15 KB
/
day13.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
const { match } = require("assert");
const fs = require("fs");
const [data1, data2] = fs
.readFileSync("day13.txt", { encoding: "utf-8" }) // read day??.txt content
.trim()
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.split("\n\n");
const coordinates = data1
.trim()
.split("\n") // Split on newline
.map((x) => {
const p = x.split(",").map(Number);
return { x: p[0], y: p[1] };
});
const foldInstructions = data2
.trim()
.split("\n") // Split on newline
.map((x) => x.match(/fold along (?<axis>[xy])=(?<position>\d+)/).groups)
.map((x) => ({ axis: x.axis, position: Number(x.position) }));
function part1() {
let points = [...coordinates.map((x) => ({ ...x }))];
let nextPoints = [];
for (const fold of foldInstructions) {
for (let i = 0; i < points.length; i++) {
const point = points[i];
if (point[fold.axis] > fold.position) {
point[fold.axis] =
(point[fold.axis] - fold.position) * -1 + fold.position;
}
nextPoints.push(point);
}
break;
}
// console.log(points);
// deduplication
const set = new Set(points.map((p) => `${p.x},${p.y}`));
// const debug = [...set];
// debug.sort();
// console.log(debug);
console.log(set.size);
}
part1();
function part2() {
let points = [...coordinates.map((x) => ({ ...x }))];
let nextPoints = [];
for (const fold of foldInstructions) {
for (let i = 0; i < points.length; i++) {
const point = points[i];
if (point[fold.axis] > fold.position) {
point[fold.axis] =
(point[fold.axis] - fold.position) * -1 + fold.position;
}
nextPoints.push(point);
}
}
// deduplication
const set = new Set(points.map((p) => `${p.x},${p.y}`));
const array = [...set].map((x) => x.split(","));
const maxX = Math.max(...array.map((x) => x[0]));
const maxY = Math.max(...array.map((x) => x[1]));
for (let j = 0; j <= maxY; j++) {
let string = "";
for (let i = 0; i <= maxX; i++) {
const key = `${i},${j}`;
if (set.has(key)) {
string += "█";
} else {
string += "·";
}
}
console.log(string);
}
}
part2();