Public
Edited
Dec 11, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
indices = input
.split("\n")
.flatMap((row, r) => Array.from(row).map((ch, c) => [ch, r, c]))
.filter(([ch, r, c]) => ch === "#")
.map(([ch, r, c]) => [r, c])
Insert cell
Insert cell
Insert cell
getExpandedMap = (dim, expandBy) => {
let indices = _.sortBy(_.uniq(dim));
let offsets = _.zip([-1, ...indices.slice(0, -1)], indices).map(
([prevIndex, index]) => index - (prevIndex + 1)
);

let offset = 0;
const expandedDim = [];

for (const [item, itemOffset] of _.zip(indices, offsets)) {
offset += itemOffset * (expandBy - 1);
expandedDim.push(item + offset);
}

return Object.fromEntries(_.zip(indices, expandedDim));
}
Insert cell
Insert cell
expandedRows = getExpandedMap(indices.map(([r, c]) => r), 2)
Insert cell
Insert cell
expandedColumns = getExpandedMap(
indices.map(([r, c]) => c),
2
)
Insert cell
Insert cell
expanded = indices.map(([r, c]) => [expandedRows[r], expandedColumns[c]])
Insert cell
Insert cell
Insert cell
distance = (g1, g2) => Math.abs(g1[0] - g2[0]) + Math.abs(g1[1] - g2[1])
Insert cell
Insert cell
upperTriangularDistanceMatrix = (galaxies) => {
const matrix = [];
for (let i = 0; i < galaxies.length; i++) {
const row = [];
for (let j = i + 1; j < galaxies.length; j++) {
row.push(distance(galaxies[i], galaxies[j]));
}
matrix.push(row);
}
return matrix;
}
Insert cell
part1 = _.sum(upperTriangularDistanceMatrix(expanded).flatMap((x) => x))
Insert cell
Insert cell
Insert cell
Insert cell
expandedMillion = {
const expandedRows = getExpandedMap(
indices.map(([r, c]) => r),
1_000_000
);
const expandedColumns = getExpandedMap(
indices.map(([r, c]) => c),
1_000_000
);
return indices.map(([r, c]) => [expandedRows[r], expandedColumns[c]]);
}
Insert cell
part2 = _.sum(upperTriangularDistanceMatrix(expandedMillion).flatMap((x) => x))
Insert cell
Insert cell
Insert cell
input = textarea || select.value
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