Not squared binary trees

Monkey see, monkey do.
I saw twitter.com/ruuddotorg/status/1441936091687239690
and did this but it's not a perfect match because I didn't do the actual leaves.

Log in to post a comment.

// LL 2021

const sides = 3; // min=1 max=3 step=1 (Left,Right,Both)
const bits = 4; // min=1 max=7 step=1
const thickness = 2; // min=1 max=3 step=1

const turtle = new Turtle();
const canvas_size = 190;

function walk(i) {
    const count = 1 << bits;
    const ii = i / thickness / thickness | 0, ix = ii % count, iy = ii / count | 0;
    const vx = i % thickness, vy = (i / thickness | 0) % thickness;
    const step = canvas_size / count, margin = step / 5, w = step - margin;
    const x = -canvas_size / 2 + step * ix + margin / 2 + vx * .2;
    const y = -canvas_size / 2 + step * iy + margin / 2 + vy * .2;
    if (sides & 1) drawTree(x, y, w, ix, 1);
    if (sides & 2) drawTree(x, y, w, count - 1 - iy, 2);
    return (i+1) < count * count * thickness * thickness;
}

function drawTree(ox, oy, w, value, side) {
    line(ox, oy, w, [0, 1], [1, 1], side);
    line(ox, oy, w, [0, 1], [0, 0], side);
    for (var i=0; i<bits; i++) {
        const dc = 1 - 1 / (bits+1) * (i+1), b = value & (1<<i);
        var mx = 0;
        for (var j=i+1; j<bits && !mx; j++) if (!(value & (1<<j))) mx = 1 - 1 / (bits+1) * (j+1);
        const dx = b ? mx : dc, dy = b ? dc : 1;
        line(ox, oy, w, [dc, dc], [dx, dy], side);
    }
}

function line(ox, oy, w, p0, p1, side) {
    if (side & 1) {
        turtle.jump(ox + p0[0] * w, oy + p0[1] * w);
        turtle.goto(ox + p1[0] * w, oy + p1[1] * w);
    } else {
        turtle.jump(ox + w - p0[0] * w, oy + w - p0[1] * w);
        turtle.goto(ox + w - p1[0] * w, oy + w - p1[1] * w);
    }
}