Recamán's sequence

Visualized in the style popularized by Numberphile.

Log in to post a comment.

const ITERATIONS = 61; // min=1, max=200, step=1
const MARGIN = 5; // min=0, max=50, step=5
const RAD_STEP = 0.1; // min=0.05, max=1.6, step=0.05

Canvas.setpenopacity(1);
const turtle = new Turtle();
turtle.jump(-100 + MARGIN, 0);

const seq = [0]
for (var i = 1; i <= ITERATIONS ; i++) { 
    let curr = seq[i - 1] - i; 
    for (var j = 0; j < i ; j++) { 
        if (seq[j] === curr || curr < 0) { 
            curr = seq[i - 1] + i;
            break;
        } 
    } 
    seq[i] = curr; 
} 

function drawHalfCircle(r, cx, cy, isAbove) {
    let endA = Math.PI * 2;
    if((isAbove && r > 0) || (!isAbove && r < 0)) 
        endA = 0;
    
    const step = Math.PI < endA ? RAD_STEP : -RAD_STEP;
    for(let a = Math.PI ; step < 0 ? a > endA : a < endA ; a += step) {
        x = cx + r * Math.cos(a);
        y = cy + r * Math.sin(a);
        turtle.goto(x, y);
    }
}

const INTERVAL = (200 - (2 * MARGIN)) / Math.max(...seq);
function walk(i) {
    const r = ((seq[i+1] - seq[i]) * INTERVAL) / 2;
    const [pX, pY] = turtle.pos();

    drawHalfCircle(r, pX + r, pY, i % 2 === 0);
    return i < (ITERATIONS - 1);
}