Public
Edited
Oct 18, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
let plt,
{ newTree } = pt;

newTree.map((d) => (d._x = d.x - Math.pow(2, d.y - 1)));

plt = Plot.plot({
x: { nice: true, type: "symlog" },
y: { nice: true },
color: { legend: true, scheme: "Blues" },
marks: [
Plot.link(
newTree.filter((d) => d.left),
{
x1: "_x",
y1: "y",
x2: (d) => newTree[d.left]._x,
y2: (d) => newTree[d.left].y
}
),
Plot.link(
newTree.filter((d) => d.right),
{
x1: "_x",
y1: "y",
x2: (d) => newTree[d.right]._x,
y2: (d) => newTree[d.right].y
}
),
Plot.dot(newTree, {
x: "_x",
y: "y",
tip: true,
fill: "orange",
stroke: "y",
r: 10
}),
Plot.text(newTree, {
x: "_x",
y: "y",
text: "v"
})
]
});

return plt;
}
Insert cell
FileAttachment("bad.png").url()
Insert cell
bad = FileAttachment("bad.png").image()
Insert cell
good = FileAttachment("good.png").image()
Insert cell
tree.map((d) => d.v).sort((a, b) => a - b)
Insert cell
pt = parseTree(tree)
Insert cell
tree = mkTree()
Insert cell
parseTree = (tree) => {
let rootPtr = 0,
output = [];

let loop = (ptr, x, y) => {
let node = tree[ptr];
Object.assign(node, { x, y });
if (node.left) {
loop(node.left, x * 2, y + 1);
}
output.push(node.v);
if (node.right) {
loop(node.right, x * 2 + 1, y + 1);
}
};

loop(rootPtr, 0, 0);

return { newTree: tree, sorted: output };
}
Insert cell
mkTree = () => {
let array = randomValues(amount),
nodes = [];

nodes.push(mkNode(array[0]));

array.slice(1).map((v) => {
// Add the v into the tree from the root
let ptr = 0;

let goto = (ptr) => {
let node = nodes[ptr];

if (v == node.v) {
node.v += 1;
}
if (v > node.v) {
if (node.right) {
goto(node.right);
} else {
nodes.push(mkNode(v));
node.right = nodes.length - 1;
}
}
if (v < node.v) {
if (node.left) {
goto(node.left);
} else {
nodes.push(mkNode(v));
node.left = nodes.length - 1;
}
}
};

goto(0);
});

return nodes;
}
Insert cell
node = mkNode(3)
Insert cell
mkNode = (v) => {
let left,
right,
count = 1;
return { v, count, left, right };
}
Insert cell
array = randomValues()
Insert cell
randomValues = (n = 100) => {
let array = [...new Array(n)]
.fill(0)
.map((_) => parseInt(Math.random() * 1000));
return array;
}
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