How to resolve the algorithm Leonardo numbers step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Leonardo numbers step by step in the JavaScript programming language

Table of Contents

Problem Statement

Leonardo numbers   are also known as the   Leonardo series.

The   Leonardo numbers   are a sequence of numbers defined by:

This task will be using the 3rd equation (above) to calculate the Leonardo numbers.

Edsger W. Dijkstra   used   Leonardo numbers   as an integral part of his   smoothsort   algorithm.

The first few Leonardo numbers are:

(The last task requirement will produce the Fibonacci numbers.)

Show all output here on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Leonardo numbers step by step in the JavaScript programming language

The provided code is a JavaScript implementation of a generator function for creating Leonardo numbers. Leonardo numbers are a sequence of numbers where each number is the sum of the previous two. The first two numbers in the sequence are 1 and 1.

The first code snippet, leoNum, uses the reduce method on an array of c numbers filled with the value add to calculate the first c Leonardo numbers. It starts with the first two numbers (l0 and l1) and then adds the next number (c) to the previous two numbers.

The second code snippet, leo, is a generator function that yields the next Leonardo number each time it is called. It takes three arguments: L0 (the first number in the sequence), L1 (the second number in the sequence), and delta (the amount to add to the previous two numbers to get the next number).

The third code snippet is a test function that prints the first 25 Leonardo numbers and the first 25 Fibonacci numbers (which are a special case of Leonardo numbers where delta is 0).

The fourth code snippet contains a number of helper functions that are used in the main code snippet.

  • indentWrapped is a function that indents and wraps a list of strings.
  • chunksOf is a function that breaks a list into chunks of a given size.
  • enumFromThenTo is a function that generates a list of numbers from a starting number to an ending number, inclusive.
  • map is a function that applies a function to every element in a list.
  • str is a function that converts an object to a string.
  • take is a function that takes the first n elements from a list or string.
  • unlines is a function that joins a list of strings into a single string.

The main function, main, uses the helper functions to format and print the first 25 Leonardo numbers and the first 25 Fibonacci numbers.

Source code in the javascript programming language

const leoNum = (c, l0 = 1, l1 = 1, add = 1) =>
    new Array(c).fill(add).reduce(
        (p, c, i) => i > 1 ? (
            p.push(p[i - 1] + p[i - 2] + c) && p
        ) : p, [l0, l1]
    );
    
console.log(leoNum(25));
console.log(leoNum(25, 0, 1, 0));


(() => {
    'use strict';

    // leo :: Int -> Int -> Int -> Generator [Int]
    function* leo(L0, L1, delta) {
        let [x, y] = [L0, L1];
        while (true) {
            yield x;
            [x, y] = [y, delta + x + y];
        }
    }

    // ----------------------- TEST ------------------------
    // main :: IO ()
    const main = () => {
        const
            leonardo = leo(1, 1, 1),
            fibonacci = leo(0, 1, 0);

        return unlines([
            'First 25 Leonardo numbers:',
            indentWrapped(take(25)(leonardo)),
            '',
            'First 25 Fibonacci numbers:',
            indentWrapped(take(25)(fibonacci))
        ]);
    };

    // -------------------- FORMATTING ---------------------

    // indentWrapped :: [Int] -> String
    const indentWrapped = xs =>
        unlines(
            map(x => '\t' + x.join(','))(
                chunksOf(16)(
                    map(str)(xs)
                )
            )
        );

    // ----------------- GENERIC FUNCTIONS -----------------

    // chunksOf :: Int -> [a] -> [[a]]
    const chunksOf = n =>
        xs => enumFromThenTo(0)(n)(
            xs.length - 1
        ).reduce(
            (a, i) => a.concat([xs.slice(i, (n + i))]),
            []
        );

    // enumFromThenTo :: Int -> Int -> Int -> [Int]
    const enumFromThenTo = x1 =>
        x2 => y => {
            const d = x2 - x1;
            return Array.from({
                length: Math.floor(y - x2) / d + 2
            }, (_, i) => x1 + (d * i));
        };

    // map :: (a -> b) -> [a] -> [b]
    const map = f =>
        // The list obtained by applying f
        // to each element of xs.
        // (The image of xs under f).
        xs => [...xs].map(f);

    // str :: a -> String
    const str = x =>
        x.toString();

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // MAIN ---
    return main();
})();


  

You may also check:How to resolve the algorithm Matrix multiplication step by step in the BQN programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Miller–Rabin primality test step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the EDSAC order code programming language
You may also check:How to resolve the algorithm Hash join step by step in the Visual FoxPro programming language