Public
Edited
Dec 1, 2023
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((line) => {
const [_, px, py, pz, vx, vy, vz, ax, ay, az] = line
.match(
/p=<(.+?),(.+?),(.+?)>,\s+v=<(.+?),(.+?),(.+?)>,\s+a=<(.+?),(.+?),(.+?)>/
)
.map(Number);
return {
P: { x: px, y: py, z: pz },
V: { x: vx, y: vy, z: vz },
A: { x: ax, y: ay, z: az }
};
});
}
Insert cell
Insert cell
function dist(vec) {
return Math.abs(vec.x) + Math.abs(vec.y) + Math.abs(vec.z);
}
Insert cell
function findClosest(particles) {
return particles.reduce(
(closestParticle, p, i) => {
const [dP, dV, dA] = [dist(p.P), dist(p.V), dist(p.A)];
const { minP, minV, minA, closest } = closestParticle;
if (
dA < minA ||
(dA === minA && dV < minV) ||
(dA === minA && dV === minV && dP < minP)
) {
return { minP: dP, minV: dV, minA: dA, closest: i };
}
return closestParticle;
},
{ minA: Infinity, minV: Infinity, minP: Infinity, closest: -1 }
).closest;
}
Insert cell
function part1(input) {
return findClosest(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function collisionSim(particles, maxTicks = 40) {
for (let tick = 0; tick < maxTicks; tick++) {
const positions = new Map();

particles.forEach((p, i) => {
["x", "y", "z"].forEach((axis) => {
p.V[axis] += p.A[axis];
p.P[axis] += p.V[axis];
});

// Log particles in dictionary of positions and particle indices.
const posStr = `${p.P.x},${p.P.y},${p.P.z}`;
if (!positions.has(posStr)) {
positions.set(posStr, []);
}
positions.get(posStr).push(i);
});

// Remove colliding particles
const collidedIndices = new Set();
for (const [_, indices] of positions) {
if (indices.length > 1) {
indices.forEach((i) => collidedIndices.add(i));
}
}
particles = particles.filter((_, i) => !collidedIndices.has(i));
}
return particles.length;
}
Insert cell
function part2(input) {
return collisionSim(parse(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