Binary Fibonacci

Draws Fibonacci numbers as lines of binary and uses a XOR bit to decide which way to turn after each iteration.

Log in to post a comment.

Canvas.setpenopacity(1);

const turtle = new Turtle();
let f0 = [false]
let f1 = [true];

function FibonacciBinary(n) {
    if (n==0) return f0;
    if (n==1) return f1;
    const next = [];
    for (let i = 0; i < f1.length; i++){
        if (f0[i] && f1[i]) {
            next[i+1] = true; // carry
        }
        else if (f0[i] || f1[i]) {
            if (next[i]) {
                next[i] = false;
                next[i+1] = true; // carry
            } else {
                next[i] = true;
            }
        }
    }
    f0 = f1;
    f1 = next;
    return next;
}

function walk(i) {
    const bits = FibonacciBinary(i);
    let xbit = false;
    bits.map(bit => {
        xbit = xbit ^ bit;
        if (bit) {
            turtle.pendown();
        }
        turtle.forward(0.05);
        turtle.penup();
    })
    if (xbit) {
        turtle.right(45);    
    }
    else {
        turtle.left(90);
    }
    return i < 1025;
}