Public
Edited
Dec 2, 2024
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((r) => [...r].map(Number));
}
Insert cell
Insert cell
function lr(r, c, grid) {
const [before, after] = AOC.splitAt(c, grid[r]);
after.shift();
return [before.reverse(), after];
}
Insert cell
Insert cell
function ud(row, col, grid) {
const before = [];
const after = [];
for (let r = 0; r < grid[0].length; r++) {
if (r < row) {
before.push(grid[r][col]);
} else if (r > row) {
after.push(grid[r][col]);
}
}
return [before.reverse(), after];
}
Insert cell
Insert cell
function isVisible(row, col, grid) {
const tree = grid[row][col];
const [l, r] = lr(row, col, grid);
const [u, d] = ud(row, col, grid);
return (
tree > Math.max(...l) ||
tree > Math.max(...r) ||
tree > Math.max(...u) ||
tree > Math.max(...d)
);
}
Insert cell
Insert cell
function part1(input) {
const grid = parse(input);
const [numRows, numCols] = [grid.length, grid[0].length];
let nVis = 2 * (numRows + numCols - 2);
for (let r = 1; r < numRows - 1; r++) {
for (let c = 1; c < numCols - 1; c++) {
nVis += isVisible(r, c, grid) ? 1 : 0;
}
}
return nVis;
}
Insert cell
Insert cell
Insert cell
Insert cell
function scenicScore(row, col, grid) {
const tree = grid[row][col];
const [l, r] = lr(row, col, grid);
const [u, d] = ud(row, col, grid);
const viewDist = (trees) => {
const lowerThan = AOC.takeWhile((t) => tree > t, trees);
return lowerThan.length + (trees[lowerThan.length] ? 1 : 0);
};
return AOC.product([viewDist(u), viewDist(l), viewDist(r), viewDist(d)]);
}
Insert cell
Insert cell
function part2(input) {
const grid = parse(input);
let maxScore = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[0].length; col++) {
maxScore = Math.max(maxScore, scenicScore(row, col, grid));
}
}
return maxScore;
}
Insert cell
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more