How to resolve the algorithm Kronecker product step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Kronecker product step by step in the JavaScript programming language

Table of Contents

Problem Statement

Implement the   Kronecker product   of two matrices (arbitrary sized) resulting in a block matrix.

Show results for each of the following two samples:

Sample 1 (from Wikipedia): Sample 2:

See implementations and results below in JavaScript and PARI/GP languages.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Kronecker product step by step in the JavaScript programming language

matkronprod.js

  • Prime function:

    • mkp arrow function: Returns the Kronecker product of the a and b matrices.
    • Both a and b must be matrices, i.e., 2D rectangular arrays.
  • Helper functions:

    • matl2cons(title, mat): Logs the title and matrix mat to the console.
    • pttl2doc(title): Prints the title to the document.
    • matp2doc(title, mat): Prints the title and matrix mat to the document.

KronProdTest.html

  • HTML file that uses the matkronprod.js script.
  • Runs the mkp function on two sample matrices and displays the results in the console and in the HTML document.

matkronprod2.js

  • Prime function:

    • mkp2(a, b) function: Returns the Kronecker product of the a and b matrices.
    • Similar to the mkp function from matkronprod.js, but implemented differently.
  • Helper functions:

    • Similar to those in matkronprod.js.

KronProdTest2.html

  • Similar to KronProdTest.html, but uses mkp2 instead of mkp to calculate the Kronecker product.

(() => { ... })()

  • JavaScript function that implements the Kronecker product using functional programming concepts.

  • Prime function:

    • kprod(xs)(ys): Returns the Kronecker product of matrices xs and ys.
  • Helper functions:

    • concat, concatMap, flip, map, mul, show, transpose, unlines: Generic functional programming functions for manipulating arrays and data structures.
  • Test code:

    • Calculates and displays the Kronecker product of two sample matrices using the kprod function.

Source code in the javascript programming language

// matkronprod.js
// Prime function:
// mkp arrow function: Return the Kronecker product of the a and b matrices.
// Note: both a and b must be matrices, i.e., 2D rectangular arrays.
mkp=(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t;
// Helper functions:
// Log title and matrix mat to console
function matl2cons(title,mat) {console.log(title); console.log(mat.join`\n`)}
// Print title to document
function pttl2doc(title) {document.write('<b>'+title+'</b><br />')}
// Print title and matrix mat to document
function matp2doc(title,mat) {
  document.write('<b>'+title+'</b>:<br />');
  for (var i = 0; i < mat.length; i++) {
    document.write('&nbsp;&nbsp;'+mat[i].join(' ')+'<br />');
  }
}


<!-- KronProdTest.html -->
<html><head>
  <title>Kronecker product: Sample 1 (from Wikipedia) and Sample 2</title>
  <script src="matkronprod.js"></script>
  <script>
  var mr,ttl='Kronecker product of A and B matrices';
  [ {a:[[1,2],[3,4]],b:[[0,5],[6,7]] },
    {a:[[0,1,0],[1,1,1],[0,1,0]],b:[[1,1,1,1],[1,0,0,1],[1,1,1,1]] }
  ].forEach(m=>{
    console.log(ttl); pttl2doc(ttl);
    matl2cons('A',m.a); matp2doc('A',m.a);
    matl2cons('B',m.b); matp2doc('B',m.b);
    mr=mkp(m.a,m.b);
    matl2cons('A x B',mr); matp2doc('A x B',mr);
    })
  </script>
</head><body></body>
</html>


// matkronprod2.js
// Prime function:
// mkp2(): Return the Kronecker product of the a and b matrices
// Note: both a and b must be matrices, i.e., 2D rectangular arrays.
function mkp2(a,b) {
  var m=a.length, n=a[0].length, p=b.length, q=b[0].length;
  var rtn=m*p, ctn=n*q; var r=new Array(rtn);
  for (var i=0; i<rtn; i++) {r[i]=new Array(ctn)
    for (var j=0;j<ctn;j++) {r[i][j]=0}
  }
  for (var i=0; i<m; i++) {
    for (var j=0; j<n; j++) {
      for (var k=0; k<p; k++) {
        for (var l=0; l<q; l++) {
          r[p*i+k][q*j+l]=a[i][j]*b[k][l];
        }}}}//all4forend
  return(r);
}
// Helper functions:
// Log title and matrix mat to console
function matl2cons(title,mat) {console.log(title); console.log(mat.join`\n`)}
// Print title to document
function pttl2doc(title) {document.write('<b>'+title+'</b><br>')}
// Print title and matrix mat to document
function matp2doc(title,mat) {
  document.write('<b>'+title+'</b>:<br>');
  for (var i=0; i < mat.length; i++) {
    document.write('&nbsp;&nbsp;'+mat[i].join(' ')+'<br>');
  }
}


<!-- KronProdTest2.html -->
<html><head>
  <title>Kronecker product v.2: Sample 1 (from Wikipedia) and Sample 2</title>
  <script src="matkronprod2.js"></script>
  <script>
  var mr,ttl='Kronecker product of A and B matrices';
  [ {a:[[1,2],[3,4]],b:[[0,5],[6,7]] },
    {a:[[0,1,0],[1,1,1],[0,1,0]],b:[[1,1,1,1],[1,0,0,1],[1,1,1,1]] }
  ].forEach(m=>{
    console.log(ttl); pttl2doc(ttl);
    matl2cons('A',m.a); matp2doc('A',m.a);
    matl2cons('B',m.b); matp2doc('B',m.b);
    mr=mkp2(m.a,m.b);
    matl2cons('A x B',mr); matp2doc('A x B',mr);
    })
  </script>
</head><body></body>
</html>


(() => {
    'use strict';

    // --------- KRONECKER PRODUCT OF TWO MATRICES ---------

    // kprod :: [[Num]] -> [[Num]] -> [[Num]]
    const kprod = xs =>
        ys => concatMap(
            compose(map(concat), transpose)
        )(
            map(map(
                flip(compose(map, map, mul))(ys)
            ))(xs)
        );

    // ----------------------- TEST ------------------------
    // main :: IO ()
    const main = () =>
        unlines(map(compose(unlines, map(show)))([
            kprod([
                [1, 2],
                [3, 4]
            ])([
                [0, 5],
                [6, 7]
            ]), [], // One empty output line
            kprod([
                [0, 1, 0],
                [1, 1, 1],
                [0, 1, 0]
            ])([
                [1, 1, 1, 1],
                [1, 0, 0, 1],
                [1, 1, 1, 1]
            ])
        ]));


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

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        x => fs.reduceRight((a, f) => f(a), x);


    // concat :: [[a]] -> [a]
    const concat = xs => [].concat.apply([], xs);


    // concatMap :: (a -> [b]) -> [a] -> [b]
    const concatMap = f =>
        xs => xs.flatMap(f);


    // flip :: (a -> b -> c) -> b -> a -> c
    const flip = f =>
        x => y => f(y)(x);


    // map :: (a -> b) -> [a] -> [b]
    const map = f =>
        xs => xs.map(f);


    // mul (*) :: Num a => a -> a -> a
    const mul = a =>
        b => a * b;


    // show :: a -> String
    const show = x =>
        JSON.stringify(x); //, null, 2);


    // transpose :: [[a]] -> [[a]]
    const transpose = xs =>
        xs[0].map((_, col) => xs.map(row => row[col]));


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


    // MAIN ---
    console.log(main());
})();


  

You may also check:How to resolve the algorithm Grayscale image step by step in the ATS programming language
You may also check:How to resolve the algorithm Dinesman's multiple-dwelling problem step by step in the Raku programming language
You may also check:How to resolve the algorithm Even or odd step by step in the Groovy programming language
You may also check:How to resolve the algorithm Plot coordinate pairs step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Create a two-dimensional array at runtime step by step in the C++ programming language