Public
Edited
Jul 24, 2023
Fork of Fibonacci
1 fork
Insert cell
Insert cell
container = container_from(canvas);
Insert cell
sketch = function( p ) {
const gArrayFibonacci = [ 0, 1, 1, 2 ];

p.setup = function() {
p.createCanvas(800, 800);
p.frameRate(2);
p.colorMode(p.HSB, 100);
showLatestFibonacciValue();
}

p.draw = function() {
p.translate(p.width/2, p.height/2);
getNextFibonacci( true );
drawRect( p.width);
showLatestFibonacciValue();
}

function drawRect(w) {
let xPos = 0;
let yPos = 0;
const scalar = w / ( 2 * getLatestFibonacciNum() );
p.background(0);

const targetArray = gArrayFibonacci;
targetArray.forEach( ( element, index ) => {
if( ( index > 0 ) && ( index < targetArray.length - 1 ) ) {

const previousIndex = index - 1;
const nextIndex = index + 1;
p.fill( ( 10 * index ) % 100, 40, 100 );

// Draw rect
p.rect( scalar * xPos, scalar * yPos,
scalar * getSign( nextIndex ) * targetArray[ previousIndex ],
scalar * getSign( index ) * element );
// Shift position
if( isOdd( index ) ){
xPos += getSign( index ) * ( element + targetArray[ previousIndex ] );
} else {
yPos += getSign( index ) * ( element + targetArray[ nextIndex ] );
}
}
});
}

// Return appropriate sign value against index
const getSign = (index) => {
const signArray = [ -1, 1, 1, -1 ];
return signArray[ index % 4 ];
}
// get next fibonacci number
// We can also register the number in the array optionally with the flag isRegister
const getNextFibonacci = (isRegister) => {

const targetArray = gArrayFibonacci;
const latestIndex = targetArray.length - 1;

const nextFibonacciNum = targetArray[ latestIndex - 1 ] + targetArray[ latestIndex ];
if( isRegister ){
targetArray.push( nextFibonacciNum );
}

return nextFibonacciNum;
}

// Get latest fibonacci number
const getLatestFibonacciNum = () => {
return gArrayFibonacci[ gArrayFibonacci.length - 1 ];
}

// The number is odd or not.
const isOdd = ( number ) => {
return ( number % 2 === 1 );
}

const showLatestFibonacciValue = () => {
const targetArray = gArrayFibonacci;
const latestIndex = targetArray.length - 1;
let text = 'Fibonacci: ' + targetArray[ latestIndex ];

if( targetArray.length > 2 ){
// Show f(n+1)/f(n)
text += ', f(' + ( latestIndex ) + ')/f(' + ( latestIndex - 1 ) + '): ' +
( targetArray[ latestIndex ] / targetArray[ latestIndex - 1 ] ).toFixed( 10 );
}

// Show it!
console.log( text );
}
}


Insert cell
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