-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday20.js
101 lines (74 loc) · 2.2 KB
/
day20.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const fs = require("fs");
const [algorithm, array] = fs
.readFileSync("day20.txt", { encoding: "utf-8" })
.split("\n\n");
const image = array.trim().split("\n");
const getDefaultChar = (y, x, image, defaultChar) => {
if (typeof image[y] !== "undefined" && typeof image[y][x] !== "undefined") {
return image[y][x];
}
return defaultChar;
};
const convolution = ({ image, algorithm, defaultChar = "." }) => {
const result = [];
for (let y = -1; y < image.length + 1; y++) {
const current = [];
for (let x = -1; x < image[0].length + 1; x++) {
let binary = "";
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const defaultCharResult =
getDefaultChar(y + i, x + j, image, defaultChar) === "#"
? "1"
: "0";
binary += defaultCharResult;
}
}
const index = parseInt(binary, 2);
current.push(algorithm[index]);
}
result.push(current.join(""));
}
return result;
};
function doubleConvolution(data) {
let { image, algorithm } = data;
let defaultChar = ".";
const img = convolution({ image, algorithm, defaultChar });
if (algorithm[0] === "#") {
defaultChar = "#";
}
return convolution({ image: img, algorithm, defaultChar });
}
function myFunction(data) {
const result = doubleConvolution(data);
countLight = result.join("").replace(/\./g, "").length;
return countLight;
}
const value = myFunction({ image, algorithm });
console.log(value);
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++= //
function multipleConvolution(data) {
let { image, algorithm, steps } = data;
let defaultChar = ".";
for (let i = 0; i < steps; i++) {
image = convolution({ image, algorithm, defaultChar });
if (defaultChar === "." && algorithm[0] === "#") {
defaultChar = "#";
} else if (defaultChar === "#" && algorithm[511] === ".") {
defaultChar = ".";
}
}
return image;
}
function myFunction2(data) {
const result = multipleConvolution(data);
countLight = result.join("").replace(/\./g, "").length;
return countLight;
}
const value2 = myFunction2({
image,
algorithm,
steps: 50,
});
console.log(value2);