Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as fs from 'fs';
- function parseFileToMatrix(filePath: string): string[][][] {
- const fileContent = fs.readFileSync(filePath, 'utf-8');
- const lines = fileContent.split("\n").map(line => line.trim().split(''));
- const matrix = [] as string[][][]
- for (let i = 0; i <= lines.length - 4; i++) {
- for (let j = 0; j <= lines.length - 4; j++) {
- const block = []
- for (let k = 0; k < 4 && i + k < lines.length; k++) {
- const row = lines[i + k].slice(j, j + 4)
- block.push(row)
- }
- matrix.push(block)
- }
- }
- return matrix
- }
- const input = parseFileToMatrix('input.txt')
- const getAllWords = (input: string[][]) => {
- const words = [] as string[]
- if (input.length < 4 || input.every(inp => inp.length < 4)) return words
- const getWordsHorizontal = (input: string[][]) => input.reduce<string[]>((acc, str) => [...acc, str.join('')], [])
- const getWordDiagonal = (input: string[][]) => {
- let word = ""
- for (let i = 0; i < input.length; i++) {
- for (let j = 0; j < input.length; j++) {
- word += input[i][j]
- }
- }
- return word
- }
- words.push(...getWordsHorizontal(input), ...getWordsHorizontal(transposeArray(input)))
- words.push(getWordDiagonal(input))
- words.push(getWordDiagonal(transposeArray(input)))
- return words
- }
- function transposeArray<T>(array: T[][]): T[][] {
- if (!array.length) return [];
- return array[0].map((_, colIndex) => array.map(row => row[colIndex]));
- }
- const ans = input.reduce((acc, inp) => [...acc, getAllWords(inp).filter(word => word === 'XMAS' || word.split('').reverse().join('') === 'XMAS')], [])
- console.log(ans.filter(a => a.length).length)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement