Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((row) => row.split(""));
}
Insert cell
Insert cell
function findEmpty(grid) {
return {
rows: grid
.map((row) => row.every((cell) => cell === "."))
.map((b, i) => (b ? i : false))
.filter(Boolean),
cols: grid[0]
.map((_, colIndex) => grid.every((row) => row[colIndex] === "."))
.map((b, i) => (b ? i : false))
.filter(Boolean)
};
}
Insert cell
Insert cell
function getStarLocations(grid) {
return grid.reduce(
(stars, row, i) =>
row.reduce((cs, c, j) => (c === "#" ? [...cs, [i, j]] : cs), stars),
[]
);
}
Insert cell
Insert cell
function dist([r1, c1], [r2, c2], empty, expan) {
const dy = empty.rows.reduce(
(acc, val) =>
Math.min(r1, r2) < val && val < Math.max(r1, r2) ? acc + expan : acc,
0
);
const dx = empty.cols.reduce(
(acc, val) =>
Math.min(c1, c2) < val && val < Math.max(c1, c2) ? acc + expan : acc,
0
);
return Math.abs(r2 - r1) + dy + Math.abs(c2 - c1) + dx;
}
Insert cell
Insert cell
function calcDistances(grid, expan) {
const stars = getStarLocations(grid);
const empty = findEmpty(grid);
return AOC.sum(
AOC.pairwiseCombinations(d3.range(stars.length)).map(([i1, i2]) =>
dist(stars[i1], stars[i2], empty, expan)
)
);
}
Insert cell
function part1(input) {
return calcDistances(parse(input), 1);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return calcDistances(parse(input), 999999);
}
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