Public
Edited
Dec 13, 2023
Insert cell
Insert cell
Insert cell
function toNumber(str) {
let n = 0;
for (let i = 0; i < str.length; i++) {
n = (n << 1) | (str[i] === "#" ? 1 : 0);
}
return n;
}
Insert cell
Insert cell
function parse(input) {
const transpose = (grid) => {
const transposed = [];
for (let col = 0; col < grid[0].length; col++) {
let newRow = "";
for (let row = 0; row < grid.length; row++) {
newRow += grid[row][col];
}
transposed.push(newRow);
}
return transposed;
};

const rowGrids = input.split("\n\n").map((block) => block.split("\n"));
const colGrids = rowGrids.map((grid) => transpose(grid));
return {
n: rowGrids.length,
rGrids: rowGrids.map((grid) => grid.map(toNumber)),
cGrids: colGrids.map((grid) => grid.map(toNumber))
};
}
Insert cell
Insert cell
function los(grid) {
const n = grid.length;
for (let row = 1; row < n; row++) {
const extent = Math.min(row, n - row); // Extent of reflection constrained by how close to top or bottom
for (let i = 1; i <= extent; i++) {
if (grid[row - i] !== grid[row + i - 1]) {
break; // Asymmetry found so move to the next canidate row
}
if (i === extent) {
return row; // Line of symmetry found
}
}
}
return 0; // No symmetry found
}
Insert cell
Insert cell
function part1(input) {
const grids = parse(input);
return grids.rGrids.reduce(
(total, rGrid, i) => total + (100 * los(rGrid) + los(grids.cGrids[i])),
0
);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function hammingDistance(n1, n2) {
let xor = n1 ^ n2;
let d = 0;
while (xor > 0) {
d += xor & 1;
xor >>= 1;
}
return d;
}
Insert cell
Insert cell
function newLoS(grid) {
const n = grid.length;
for (let row = 1; row < n; row++) {
let [smudges, pairs] = [0, 0];
const extent = Math.min(row, n - row);
for (let i = 0; i < extent; i++) {
const diff = hammingDistance(grid[row - i - 1], grid[row + i]);
if (diff === 1) {
smudges++;
if (smudges > 1) {
break; // More than one smudge required for symmetry, so it's not here.
}
} else if (diff === 0) {
pairs++;
}
}
if (smudges === 1 && pairs === extent - 1) {
return row; // A one-smudge line of symmetry found
}
}
return 0; // No new symmetry found
}
Insert cell
function part2(input) {
const grids = parse(input);
return grids.rGrids.reduce(
(total, rGrid, i) =>
total + (100 * newLoS(rGrid) + newLoS(grids.cGrids[i])),
0
);
}
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