Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
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
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
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

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