Published
Edited
Dec 18, 2021
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
part2 = d3.max(combinations(data), ([a, b]) => magnitude(add(a, b)))
Insert cell
function* combinations(r) {
for (let i = 0; i < r.length; i++)
for (let j = i + 1; j < r.length; j++) {
yield [r[i], r[j]];
yield [r[j], r[i]];
}
}
Insert cell
part1 = magnitude(data.reduce(add))
Insert cell
function magnitude(node) {
if (typeof node === "string") node = JSON.parse(node)
if (!Array.isArray(node)) return node;
return 3 * magnitude(node[0]) + 2 * magnitude(node[1]);
}
Insert cell
data = test.trim().split("\n").map((s) => s.trim())
Insert cell
add = (a, b) => reduce(`[${a},${b}]`)
Insert cell
function reduce(s) {
while (true) {
const previous = s;
if ((s = explode(s)) !== previous) continue;
if ((s = split(s)) !== previous) continue;
return previous;
}
}
Insert cell
function split(s) {
return s.replace(
/(\d\d+)/, // 10+
(d) => `[${Math.floor(+d / 2)},${Math.ceil(+d / 2)}]`
);
}
Insert cell
function explode(s) {
let opens = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "[") opens++;
else if (s[i] === "]") opens--;
else if (opens >= 5) {
const [x, l, r] = s.slice(i).match(/(\d+),(\d+)/);
const left = s
.slice(0, i - 1)
.replace(/(\d+)(\D+)$/, (m, d, p) => `${+d + +l}${p}`);
const right = s.slice(i + x.length + 1).replace(/(\d+)/, (d) => +d + +r);
return `${left}0${right}`;
}
}
return s;
}
Insert cell
splitTest = `
[10,[3,2]]
[10]
[2,[4,[10,11]]]
[2,[4,[[5,5],11]]]
`
.trim()
.split("\n")
.map((s) => s.trim())
.map(split)
Insert cell
explodeTest = `
[[[[[9,8],1],2],3],4]
[7,[6,[5,[4,[3,2]]]]]
[[6,[5,[4,[3,2]]]],1]
[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]
[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]
`
.trim()
.split("\n")
.map((s) => s.trim())
.map(explode)
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