-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.ts
96 lines (78 loc) · 2.42 KB
/
4.ts
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
import * as fs from "fs";
// const input = `MMMSXXMASM
// MSAMXMSMSA
// AMXSXMAAMM
// MSAMASMSMX
// XMASAMXAMM
// XXAMMXXAMA
// SMSMSASXSS
// SAXAMASAAA
// MAMMMXMMMM
// MXMXAXMASX`;
const input = fs.readFileSync("4-input.txt", "utf8");
const lines = input.split("\n");
const search = (i: number, j: number, nextChar: string, xDir: number, yDir: number): boolean => {
i += yDir;
j += xDir;
if (i < 0 || j < 0) {
return false;
}
if (i >= lines.length || j >= lines[i].length) {
return false;
}
if (lines[i][j] !== nextChar) {
return false;
}
if (nextChar === "S") {
return true;
}
let newNextChar = "";
if (nextChar === "M") {
newNextChar = "A";
}
if (nextChar === "A") {
newNextChar = "S";
}
return search(i, j, newNextChar, xDir, yDir);
};
const part1 = () => {
let count: number = 0;
for (let i = 0; i < lines.length; i++) {
for (let j = 0; j < lines[i].length; j++) {
const c = lines[i][j];
if (c === "X") {
search(i, j, "M", 0, 1) && (count += 1); // up
search(i, j, "M", 1, 1) && (count += 1); // diag top-right
search(i, j, "M", 1, 0) && (count += 1); // right
search(i, j, "M", 1, -1) && (count += 1); // diag bottom-right
search(i, j, "M", 0, -1) && (count += 1); // down
search(i, j, "M", -1, -1) && (count += 1); // diag bottom-left
search(i, j, "M", -1, 0) && (count += 1); // left
search(i, j, "M", -1, 1) && (count += 1); // diag top-left
}
}
}
return count;
};
const part2 = () => {
let count: number = 0;
for (let i = 0; i < lines.length; i++) {
for (let j = 0; j < lines[i].length; j++) {
const c = lines[i][j];
if (c === "A") {
const tl = lines[i - 1]?.[j - 1];
const br = lines[i + 1]?.[j + 1];
const bl = lines[i + 1]?.[j - 1];
const tr = lines[i - 1]?.[j + 1];
const ltMatch = (tl === "M" && br === "S") || (tl === "S" && br === "M");
const blMatch = (bl === "M" && tr === "S") || (bl === "S" && tr === "M");
if (ltMatch && blMatch) {
count += 1;
}
}
}
}
return count;
};
console.log(part1());
console.log(part2());