Public
Edited
Sep 26, 2023
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function distToOrigin(n) {
const ring = Math.ceil((Math.sqrt(n) - 1) / 2);
const prevRing = Math.pow(2 * ring - 1, 2);
const closestMidpoint = [2, 4, 6, 8]
.map((d) => prevRing + ring + d * ring)
.reduce((acc, curr) =>
Math.abs(curr - n) < Math.abs(acc - n) ? curr : acc
);
return ring + Math.abs(n - closestMidpoint);
}
Insert cell
function part1(input) {
return distToOrigin(input);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function cumulativeSpiralLargerThan(target) {
let grid = { "0,0": 1 };
let adj = AOC.gAdjacency(); // Generates array of adjaceny offsets [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1]... [1,1]]
let n = 1;

while (true) {
const root = Math.floor(Math.sqrt(n));
const ring = Math.floor((root + (root % 2)) / 2);
const maxInRing = 4 * ring * ring;
const offset = n - maxInRing;
let x, y;
if (n <= maxInRing - 2 * ring) {
x = offset + 3 * ring;
y = ring;
} else if (n <= maxInRing) {
x = ring;
y = -offset - ring;
} else if (n <= maxInRing + 2 * ring) {
x = ring - offset;
y = -ring;
} else {
x = -ring;
y = offset - 3 * ring;
}

let sum = adj.reduce(
(acc, [dx, dy]) => acc + (grid[`${x + dx},${y + dy}`] || 0),
0
);
if (sum > target) {
return sum;
}
grid[`${x},${y}`] = sum;
n++;
}
}
Insert cell
function part2(input) {
return cumulativeSpiralLargerThan(input);
}
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