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 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
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

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