How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the JavaScript programming language

Table of Contents

Problem Statement

Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the JavaScript programming language

The provided JavaScript code defines a function called lowerTriangle that extracts the lower triangle of a square matrix. It uses the Either data type to handle the case when the input matrix is not square.

Key Concepts:

  • Either Data Type: The Either data type represents a value that can be either a "Left" value (an error message) or a "Right" value (the result).
  • Square Matrix: A square matrix has the same number of rows and columns.
  • Lower Triangle: The lower triangle of a matrix contains all elements below the main diagonal (from top-right to bottom-left).

Implementation:

1. Lower Triangle Function (lowerTriangle):

  • Takes a matrix as input and returns an Either value.
  • If the matrix is square, it calculates the lower triangle by iteratively slicing rows from the top.
  • If the matrix is not square, it returns a Left value with an error message.

2. Square Matrix Check (isSquare):

  • Checks if a matrix is square by comparing the number of rows to the length of each row.

3. Either Handling Functions:

  • Left: Creates a Left value.
  • Right: Creates a Right value.
  • either: Applies a function to either the Left or Right value of an Either value based on its type.

4. Sum Calculation (sum):

  • Calculates the sum of a list of numbers.

Usage:

  • The main function calls lowerTriangle on a 5x5 square matrix, extracts the lower triangle, and sums all its elements.
  • The program prints the result if the input matrix is valid or displays an error message otherwise.

Example:

Given the input matrix:

[
   [1, 3, 7, 8, 10],
   [2, 4, 16, 14, 4],
   [3, 1, 9, 18, 11],
   [12, 14, 17, 18, 20],
   [7, 1, 3, 9, 5]
]

The output would be:

Lower triangular sum: 113

Source code in the javascript programming language

(() => {
    "use strict";

    // -------- LOWER TRIANGLE OF A SQUARE MATRIX --------

    // lowerTriangle :: [[a]] -> Either String [[a]]
    const lowerTriangle = matrix =>
        // Either a message, if the matrix is not square,
        // or the lower triangle of the matrix.
        isSquare(matrix) ? (
            Right(
                matrix.reduce(
                    ([n, rows], xs) => [
                        1 + n,
                        rows.concat([xs.slice(0, n)])
                    ],
                    [0, []]
                )[1]
            )
        ) : Left("Not a square matrix");


    // isSquare :: [[a]] -> Bool
    const isSquare = rows => {
        // True if the length of every row in the matrix
        // matches the number of rows in the matrix.
        const n = rows.length;

        return rows.every(x => n === x.length);
    };

    // ---------------------- TEST -----------------------
    const main = () =>
        either(
            msg => `Lower triangle undefined :: ${msg}`
        )(
            rows => sum([].concat(...rows))
        )(
            lowerTriangle([
                [1, 3, 7, 8, 10],
                [2, 4, 16, 14, 4],
                [3, 1, 9, 18, 11],
                [12, 14, 17, 18, 20],
                [7, 1, 3, 9, 5]
            ])
        );

    // --------------------- GENERIC ---------------------

    // Left :: a -> Either a b
    const Left = x => ({
        type: "Either",
        Left: x
    });


    // Right :: b -> Either a b
    const Right = x => ({
        type: "Either",
        Right: x
    });


    // either :: (a -> c) -> (b -> c) -> Either a b -> c
    const either = fl =>
        // Application of the function fl to the
        // contents of any Left value in e, or
        // the application of fr to its Right value.
        fr => e => e.Left ? (
            fl(e.Left)
        ) : fr(e.Right);


    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

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


  

You may also check:How to resolve the algorithm Faulhaber's triangle step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sequence: smallest number with exactly n divisors step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Last letter-first letter step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Bioinformatics/base count step by step in the JavaScript programming language