66 lines
1.7 KiB
JavaScript
66 lines
1.7 KiB
JavaScript
|
|
||
|
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 getScenicScore = (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).reverse();
|
||
|
const right = matrix[y].slice(x + 1);
|
||
|
const bottom = rotatedMatrix[rY].slice(0, rX).reverse();
|
||
|
const top = rotatedMatrix[rY].slice(rX + 1);
|
||
|
|
||
|
const directions = [left, right, bottom, top];
|
||
|
|
||
|
return directions.map(trees => {
|
||
|
const distance = trees.findIndex(tree => tree >= height) + 1;
|
||
|
return distance || trees.length;
|
||
|
}).reduce((product, score) => score * product, 1);
|
||
|
|
||
|
};
|
||
|
|
||
|
//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) {
|
||
|
const score = getScenicScore(matrix, rotatedMatrix, x, y);
|
||
|
answer = Math.max(answer, score);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
console.log(answer);
|
||
|
})();
|