|
| 1 | +const input = `MMMSXXMASM |
| 2 | +MSAMXMSMSA |
| 3 | +AMXSXMAAMM |
| 4 | +MSAMASMSMX |
| 5 | +XMASAMXAMM |
| 6 | +XXAMMXXAMA |
| 7 | +SMSMSASXSS |
| 8 | +SAXAMASAAA |
| 9 | +MAMMMXMMMM |
| 10 | +MXMXAXMASX`; |
| 11 | +const table = input.split("\n").map((row) => row.split("")); |
| 12 | +const rows = table.length; |
| 13 | +const cols = table[0]?.length; |
| 14 | +const word = "XMAS".split(""); |
| 15 | +let count = 0; |
| 16 | + |
| 17 | +for (let i = 0; i < rows; i++) { |
| 18 | + for (let j = 0; j < rows; j++) { |
| 19 | + // Find horizontal |
| 20 | + const horizon = (idx: number) => table?.[i]?.[j + idx]; |
| 21 | + const horizonInv = (idx: number) => table?.[i]?.[j - idx]; |
| 22 | + |
| 23 | + if (word.every((char, idx) => char === horizon(idx))) count++; |
| 24 | + if (word.every((char, idx) => char === horizonInv(idx))) count++; |
| 25 | + |
| 26 | + // Find vertical |
| 27 | + const vert = (idx: number) => table?.[i + idx]?.[j]; |
| 28 | + const vertInv = (idx: number) => table?.[i - idx]?.[j]; |
| 29 | + |
| 30 | + if (word.every((char, idx) => char === vert(idx))) count++; |
| 31 | + if (word.every((char, idx) => char === vertInv(idx))) count++; |
| 32 | + |
| 33 | + // Find diagonal |
| 34 | + const diagTopLeft = (idx: number) => table?.[i + idx]?.[j + idx]; |
| 35 | + const diagTopRight = (idx: number) => table?.[i + idx]?.[j - idx]; |
| 36 | + const diagBottomLeft = (idx: number) => table?.[i - idx]?.[j + idx]; |
| 37 | + const diagBottomRight = (idx: number) => table?.[i - idx]?.[j - idx]; |
| 38 | + |
| 39 | + if (word.every((char, idx) => char === diagTopLeft(idx))) count++; |
| 40 | + if (word.every((char, idx) => char === diagTopRight(idx))) count++; |
| 41 | + if (word.every((char, idx) => char === diagBottomLeft(idx))) count++; |
| 42 | + if (word.every((char, idx) => char === diagBottomRight(idx))) count++; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +console.log(count); |
0 commit comments