Public
Edited
Dec 11, 2023
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
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
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more