How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the JavaScript programming language

Table of Contents

Problem Statement

Print out the first   15   Catalan numbers by extracting them from Pascal's triangle.

Pascal's triangle

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the JavaScript programming language

Approach 1 (Vanilla JavaScript):

  • Initialize n with the value 15.
  • Use a for loop to iterate from 1 to n, inclusive.
  • For each iteration, perform the following steps:
    • Create an array t with two initial values: 0 and 1.
    • Iterate from 1 to j, where j is initially i and is decremented down to 1. For each iteration, add t[j] to t[j - 1]. This effectively computes the cumulative sum of t.
    • Add a new element to t with the value t[i].
    • Iterate from i + 1 to j, where j is still decremented down to 1. For each iteration, add t[j] to t[j - 1]. This computes the cumulative sum of elements after t[i].
    • Write the difference between t[i + 1] and t[i] to the document, separated by commas for values greater than 1.
  • The result is a comma-separated list of Catalan numbers from 1 to 15.

Approach 2 (Functional Programming):

  • Catalan Series:
    • Defines a function catalanSeries that takes an integer n and returns an array of Catalan numbers up to n.
    • Uses the alternate function to alternate the elements of the Pascal's triangle.
    • Uses the diff function to calculate the difference between two adjacent elements in an array.
    • Computes the Catalan numbers by alternating the elements of Pascal's triangle at level 2n and then taking the differences between adjacent elements.
  • Pascal's Triangle:
    • Defines a function pascal that takes an integer n and returns the nth row of Pascal's triangle.
    • Uses the until function to iterate until the level is less than or equal to 1.
    • Computes each row by zipping the adjacent rows with the + operator and adding 0s to the beginning and end of each row.
  • Generic Functions:
    • zipWith zips two arrays together using the provided function.
    • until iterates a function until a given predicate is met.
    • drop drops the first n elements from an array.
    • tail removes the first element from an array.
  • The code calls tail(catalanSeries(16)) to get the Catalan numbers from 1 to 15 and then prints them to the console.

Output:

Both approaches produce the same output:

[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]

These are the first 15 Catalan numbers.

Source code in the javascript programming language

var n = 15;
for (var t = [0, 1], i = 1; i <= n; i++) {
    for (var j = i; j > 1; j--) t[j] += t[j - 1];
    t[i + 1] = t[i];
    for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];
    document.write(i == 1 ? '' : ', ', t[i + 1] - t[i]);
}


(() => {
    'use strict';

    // CATALAN

    // catalanSeries :: Int -> [Int]
    let catalanSeries = n => {
        let alternate = xs => xs.reduce(
                (a, x, i) => i % 2 === 0 ? a.concat([x]) : a, []
            ),
            diff = xs => xs.length > 1 ? xs[0] - xs[1] : xs[0];

        return alternate(pascal(n * 2))
            .map((xs, i) => diff(drop(i, xs)));
    }

    // PASCAL

    // pascal :: Int -> [[Int]]
    let pascal = n => until(
            m => m.level <= 1,
            m => {
                let nxt = zipWith(
                    (a, b) => a + b, [0].concat(m.row), m.row.concat(0)
                );
                return {
                    row: nxt,
                    triangle: m.triangle.concat([nxt]),
                    level: m.level - 1
                }
            }, {
                level: n,
                row: [1],
                triangle: [
                    [1]
                ]
            }
        )
        .triangle;


    // GENERIC FUNCTIONS

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    let zipWith = (f, xs, ys) =>
        xs.length === ys.length ? (
            xs.map((x, i) => f(x, ys[i]))
        ) : undefined;

    // until :: (a -> Bool) -> (a -> a) -> a -> a
    let until = (p, f, x) => {
        let v = x;
        while (!p(v)) v = f(v);
        return v;
    }

    // drop :: Int -> [a] -> [a]
    let drop = (n, xs) => xs.slice(n);

    // tail :: [a] -> [a]
    let tail = xs => xs.length ? xs.slice(1) : undefined;

    return tail(catalanSeries(16));
})();


[1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845]


  

You may also check:How to resolve the algorithm Fibonacci word step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Factorial step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Named parameters step by step in the JavaScript programming language
You may also check:How to resolve the algorithm 4-rings or 4-squares puzzle step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Abundant odd numbers step by step in the JavaScript programming language