-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday4pt2.ts
95 lines (65 loc) · 1.7 KB
/
day4pt2.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
export const input = await Deno.readTextFile('./day4input.txt')
// const input = `MMMSXXMASM
// MSAMXMSMSA
// AMXSXMAAMM
// MSAMASMSMX
// XMASAMXAMM
// XXAMMXXAMA
// SMSMSASXSS
// SAXAMASAAA
// MAMMMXMMMM
// MXMXAXMASX`
// console.log(input)
const pattern= /\n/g
const rowItems = input.split(pattern)
const rowsCount = rowItems.length
console.log(rowsCount)
const colsCount = rowItems[0].length
console.log(colsCount)
let xmasMatrix = rowItems
.map(rowItem => rowItem.split(''))
let totalSum = 0
xmasMatrix
.forEach((rowItem, rowIdx) => {
console.log("Row Item List:", rowItem)
rowItem.forEach((cellItem, colIdx) => {
if (cellItem === 'A') {
const diags = getDiagonals()
let surroundWords = []
for (let diag in diags) {
// console.log(diag, diags[diag])
let wordChars = []
let xC
let yC
const directions = diags[diag]
for (let dir in directions) {
// console.log(dir, directions[dir])
xC = rowIdx + directions[dir][0]
yC = colIdx + directions[dir][1]
if (xC < 0 || xC > colsCount-1 || yC < 0 || yC > colsCount-1 ) continue
wordChars.push(xmasMatrix[xC][yC])
}
if (!wordChars.length) continue
surroundWords.push(wordChars)
}
console.log(cellItem, xmasMatrix[rowIdx][colIdx])
let matchedWords = surroundWords.map(_ => _.join('A')).filter(_ => _ === 'MAS' || _ === 'SAM')
console.log(surroundWords, matchedWords, matchedWords.length)
if (matchedWords.length === 2)
totalSum += 1
}
})
})
console.log(totalSum)
function getDiagonals () {
return [
{
upleft: [ -1, -1 ],
downright: [ 1, 1 ]
},
{
upright: [ -1, 1 ],
downleft: [ 1, -1 ]
}
]
}