Public
Edited
Dec 14, 2023
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((row) => row.split(""));
}
Insert cell
Insert cell
function rotate(grid) {
return grid[0]
.map((_, col) => grid.map((row) => row[col]))
.map((row) => row.reverse());
}
Insert cell
Insert cell
function tilt(grid) {
for (const row of grid) {
for (let i = row.length - 1; i >= 0; i--) {
if (row[i] !== ".") {
continue;
}
for (let j = i - 1; j >= 0; j--) {
if (row[j] === "#") {
break; // No rock to roll
}
if (row[j] === "O") {
row[i] = "O";
row[j] = ".";
break; // We've moved the rock as far as it will go
}
}
}
}
return grid;
}
Insert cell
Insert cell
function load(grid) {
let total = 0;
for (const row of grid) {
for (let col = 0; col < row.length; col++) {
if (row[col] === "O") {
total += col + 1;
}
}
}
return total;
}
Insert cell
Insert cell
function part1(input) {
const originalGrid = parse(input);
return load(tilt(rotate(originalGrid)));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function spinCycle(grid) {
let g = grid;
for (let i = 0; i < 4; i++) {
g = tilt(rotate(g));
}
return g;
}
Insert cell
Insert cell
function cycleSequence(grid) {
const loads = [];
// 200 spin cycles is enough to detect 2 full repeat sequences
for (let i = 0; i < 200; i++) {
grid = spinCycle(grid);
loads.push(load(rotate(grid)));
}

const [len, offset] = AOC.arrayCycle(loads);
const n = offset + ((1000000000 - offset) % len);

grid = parse(puzzleInput);
for (let i = 0; i < n; i++) {
grid = spinCycle(grid);
}
return grid;
}
Insert cell
function part2(input) {
return load(rotate(cycleSequence(parse(input))));
}
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