Public
Edited
Dec 21, 2022
1 star
Insert cell
Insert cell
R = import(
"https://cdn.jsdelivr.net/npm/@observablehq/runtime@5/dist/runtime.js"
)
Insert cell
function yell(ops) {
const module = new R.Runtime().module();
for (const l of ops.trim().split("\n")) {
const [monkey, op] = l.split(": ");
const vars = Array.from(op.matchAll(/[a-z]+/g), ([d]) => d);
module
.variable()
.define([monkey], vars, Function(vars.join(","), `return ${op}`));
}
return module.value("root");
}
Insert cell
yell(sample)
Insert cell
yell(input)
Insert cell
Insert cell
solve((solution) => yell2(sample, solution).value("root"), 0)
Insert cell
s0 = solve((solution) => yell2(input, solution).value("root"), 0)
Insert cell
solution = s0.x
Insert cell
yell2(input, solution).value("root")
Insert cell
// async Newton-Raphson the thing… super slow but hey
async function solve(f, y, x) {
const epsilon = 0.01;
const { abs } = Math;
var steps = 100,
delta,
f0,
f1;
x = x === undefined ? 0 : +x;
y = +y;
do {
f0 = await f(x);
f1 = await f(x + epsilon);
if (f0 === f1) f1 = f0 + epsilon;
x -= delta = (-1 * epsilon * (f0 - y)) / (f0 - f1);
} while (steps-- > 0 && abs(delta) > epsilon);
return steps < 0 ? NaN : { steps, x };
}
Insert cell
function yell2(ops, t) {
const module = new R.Runtime().module();
for (const l of ops.trim().split("\n")) {
const [monkey, op] = l.split(": ");
const vars = Array.from(op.matchAll(/[a-z]+/g), ([d]) => d);
module
.variable()
.define(
[monkey],
monkey === "humn" ? [] : vars,
monkey === "humn"
? t
: monkey === "root"
? (a, b) => a - b
: Function(vars.join(","), `return ${op}`)
);
}
return module;
}
Insert cell
Insert cell
F = yell3(input).value("root")
Insert cell
Insert cell
Insert cell
1544459888147072 / 416
Insert cell
function yell3(ops) {
const module = new R.Runtime().module();
for (const l of ops.trim().split("\n")) {
let [monkey, op] = l.split(": ");
const vars = Array.from(op.matchAll(/[a-z]+/g), ([d]) => d);
// op = op.replaceAll(" ", "");
for (const v of vars) op = op.replace(v, `"+ ${v} + "`);
module
.variable()
.define(
[monkey],
monkey === "humn" ? [] : vars,
monkey === "humn"
? `x`
: monkey === "root"
? (a, b) => `(${a}) - (${b})`
: Function(
vars.join(","),
`return ([${vars}].some(v => typeof v === "string") ? "(${op})" : eval("${op}"))`
)
);
}
return module;
}
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