Public
Edited
Dec 7
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((d) => {
const nums = d.split(" ");
return {
result: Number(nums[0].slice(0, -1)),
operands: nums.slice(1).reverse().map(Number)
};
});
}
Insert cell
Insert cell
function validExpr(total, operands) {
if (operands.length === 1) {
return operands[0] === total;
}

const [canDiv, canSub] = [total % operands[0] === 0, total >= operands[0]];

if (!canDiv && !canSub) {
return false;
}

return (
(canDiv && validExpr(total / operands[0], operands.slice(1))) ||
(canSub && validExpr(total - operands[0], operands.slice(1)))
);
}
Insert cell
Insert cell
function part1(input) {
return d3.sum(
parse(input).filter((d) => validExpr(d.result, d.operands)),
(d) => d.result
);
}
Insert cell
Insert cell
Insert cell
Insert cell
function validExpr2(total, operands) {
if (operands.length === 1) {
return operands[0] === total;
}

const canDiv = total % operands[0] === 0;
const canSub = total >= operands[0];
const canCat = String(total).endsWith(operands[0]);

if (!canDiv && !canSub && !canCat) {
return false;
}

return (
(canDiv && validExpr2(total / operands[0], operands.slice(1))) ||
(canSub && validExpr2(total - operands[0], operands.slice(1))) ||
(canCat &&
validExpr2(
Number(String(total).slice(0, -String(operands[0]).length)),
operands.slice(1)
))
);
}
Insert cell
function part2(input) {
return d3.sum(
parse(input).filter((d) => validExpr2(d.result, d.operands)),
(d) => d.result
);
}
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