Advertisement
_joel1024

Untitled

Dec 5th, 2024
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import * as fs from 'fs';
  2.  
  3. function parseFileToMatrix(filePath: string): string[][][] {
  4.     const fileContent = fs.readFileSync(filePath, 'utf-8');
  5.     const lines = fileContent.split("\n").map(line => line.trim().split(''));
  6.  
  7.     const matrix = [] as string[][][]
  8.  
  9.     for (let i = 0; i <= lines.length - 4; i++) {
  10.         for (let j = 0; j <= lines.length - 4; j++) {
  11.             const block = []
  12.  
  13.             for (let k = 0; k < 4 && i + k < lines.length; k++) {
  14.                 const row = lines[i + k].slice(j, j + 4)
  15.                 block.push(row)
  16.             }
  17.             matrix.push(block)
  18.         }
  19.     }
  20.  
  21.     return matrix
  22. }
  23.  
  24. const input = parseFileToMatrix('input.txt')
  25.  
  26. const getAllWords = (input: string[][]) => {
  27.     const words = [] as string[]
  28.     if (input.length < 4 || input.every(inp => inp.length < 4)) return words
  29.  
  30.     const getWordsHorizontal = (input: string[][]) => input.reduce<string[]>((acc, str) => [...acc, str.join('')], [])
  31.     const getWordDiagonal = (input: string[][]) => {
  32.         let word = ""
  33.         for (let i = 0; i < input.length; i++) {
  34.             for (let j = 0; j < input.length; j++) {
  35.                 word += input[i][j]
  36.             }
  37.         }
  38.         return word
  39.     }
  40.  
  41.     words.push(...getWordsHorizontal(input), ...getWordsHorizontal(transposeArray(input)))
  42.     words.push(getWordDiagonal(input))
  43.     words.push(getWordDiagonal(transposeArray(input)))
  44.  
  45.     return words
  46. }
  47.  
  48. function transposeArray<T>(array: T[][]): T[][] {
  49.     if (!array.length) return [];
  50.  
  51.     return array[0].map((_, colIndex) => array.map(row => row[colIndex]));
  52. }
  53.  
  54. const ans = input.reduce((acc, inp) => [...acc, getAllWords(inp).filter(word => word === 'XMAS' || word.split('').reverse().join('') === 'XMAS')], [])
  55.  
  56. console.log(ans.filter(a => a.length).length)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement