Public
Edited
Dec 1, 2023
Insert cell
Insert cell
Insert cell
function buildGrid(input) {
const lines = input.split("\n").slice(2); // Skip the headers
const grd = [];
for (const line of lines) {
const [_, c, r, u, a] = line
.match(/node-x(\d+)-y(\d+).*T\s+(\d+)T\s+(\d+)T/)
.map(Number);
if (!grd[r]) {
grd[r] = [];
}
grd[r][c] = { u, a };
}
return grd;
}
Insert cell
Insert cell
function countViablePairs(grid) {
let n = 0;
for (let r1 = 0; r1 < grid.length; r1++) {
for (let c1 = 0; c1 < grid[0].length; c1++) {
if (grid[r1][c1].u !== 0) {
for (let r2 = 0; r2 < grid.length; r2++) {
for (let c2 = 0; c2 < grid[0].length; c2++) {
if (grid[r1][c1].u <= grid[r2][c2].a && (c1 !== c2 || r1 !== r2)) {
n++;
}
}
}
}
}
}
return n;
}
Insert cell
function part1(input) {
return countViablePairs(buildGrid(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function swappableGrid(grd) {
return AOC.gMap((d) => d.u < 100, grd);
}
Insert cell
Insert cell
function nodeId(row, col) {
return `n-${row}-${col}`;
}
Insert cell
Insert cell
function buildGraph(capacityGrid) {
const graph = new Graph();
const grd = swappableGrid(capacityGrid);

for (let row = 0; row < grd.length; row++) {
for (let col = 0; col < grd[0].length; col++) {
if (grd[row][col]) {
const currentNodeId = nodeId(row, col);
if (grd[row][col - 1]) {
graph.addEdge(currentNodeId, nodeId(row, col - 1));
}
if (grd[row][col + 1]) {
graph.addEdge(currentNodeId, nodeId(row, col + 1));
}
if (grd[row - 1] && grd[row - 1][col]) {
graph.addEdge(currentNodeId, nodeId(row - 1, col));
}
if (grd[row + 1] && grd[row + 1][col]) {
graph.addEdge(currentNodeId, nodeId(row + 1, col));
}
}
}
}
return graph;
}
Insert cell
Insert cell
function emptyCell(grd) {
for (let row = 0; row < grd.length; row++) {
for (let col = 0; col < grd[0].length; col++) {
if (grd[row][col].u === 0) {
return nodeId(row, col);
}
}
}
}
Insert cell
Insert cell
function stepsToTR(grd) {
const graph = buildGraph(grd);
const start = emptyCell(grd);
const end = nodeId(0, grd[0].length - 2); // Cell to the left of the top-right corner
return graph.shortestPath(start, end).length;
}
Insert cell
Insert cell
function part2(input) {
const grd = buildGrid(input);
return stepsToTR(grd) + 5 * (grd[0].length - 2);
}
Insert cell
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