Public
Edited
Dec 11, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
function leastCost(input, cost) {
const candidatePos = AOC.sort([...new Set(input.map(AOC.identity))]);

let prevCost = cost(candidatePos[0], input);
let nextCost = cost(candidatePos[1], input);
let pos = 1;

while (nextCost < prevCost) {
prevCost = nextCost;
nextCost = cost(++pos, input);
}
return prevCost;
}
Insert cell
function part1(input) {
const cost = (pos, crabs) => AOC.sum(crabs.map((c) => Math.abs(c - pos)));
return leastCost(input, cost);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const triangular = (n) => (n * (n + 1)) / 2;
const cost = (pos, crabs) =>
AOC.sum(crabs.map((c) => triangular(Math.abs(c - pos))));

return leastCost(input, cost);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part1a(input) {
const cost = (pos, crabs) => AOC.sum(crabs.map((c) => Math.abs(c - pos)));
return cost(AOC.median(input), input);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2a(input) {
const triangular = (n) => (n * (n + 1)) / 2;
const cost = (pos, crabs) =>
AOC.sum(crabs.map((c) => triangular(Math.abs(c - pos))));
const mean = AOC.mean(input);
return Math.min(cost(Math.floor(mean), input), cost(Math.ceil(mean), 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