const fs = require('fs/promises'); let answer = 0; const rotate90 = (matrix) => { const result = matrix[matrix.length - 1].map(x => [x]) ; for (const row of (matrix.slice(0, -1).reverse())) { for(const [i, columns] of result.entries()) { columns.push(row[i]); } }; return result; } const isVisible = (matrix, rotatedMatrix, x, y) => { const height = matrix[y][x]; const rY = x; const rX = matrix.length - y - 1; const left = matrix[y].slice(0, x); if(Math.max(...left) < height) { return 1; } const right = matrix[y].slice(x + 1); if(Math.max(...right) < height) { return 1; } const bottom = rotatedMatrix[rY].slice(0, rX); if(Math.max(...bottom) < height) { return 1; } const top = rotatedMatrix[rY].slice(rX + 1); if(Math.max(...top) < height) { return 1; } return 0; }; //1234 //5678 //9012 const countVisible = (matrix) => { return matrix.reduce((count, row) => { const [_, rowCount] = row.reduce(([tallest, count], tree) => { return [Math.max(tree, tallest), tree > tallest ? count+1: count]; }, [-1, 0]); return count + rowCount; },0); } (async () => { const input = await fs.readFile("./input.txt", 'utf8'); //const input = "1234\n5678\n9012"; const lines = input.split("\n"); const matrix = lines.map(line => line.split("").map(x => parseFloat(x))).filter(x => x.length); const rotatedMatrix = rotate90(matrix); for(let y = 0; y < matrix.length; ++y) { for(let x = 0; x < matrix[0].length; ++x) { if(isVisible(matrix, rotatedMatrix, x, y)) { ++answer } } } console.log(answer); })();