Multiplication of two matrix in kotlin

Kotlin program for Multiplication of two matrix. Here mentioned other language solution.
/*
Kotlin program for
Two matrix multiplication
*/
class Multiply
{
companion object
{
// Display the element of given 2d matrix
fun printRecord(matrix: Array < Array < Int >> ): Unit
{
println(" --------------");
// Assume N x N Matrix size
val row: Int = matrix.count();
val col: Int = matrix[0].count();
var i: Int = 0;
// Iterate the row element
while (i < row)
{
var j: Int = 0;
// Iterate the column element
while (j < col)
{
// Display element value
print(" " + matrix[i][j]);
j += 1;
}
// Add new line
println();
i += 1;
}
println();
}
fun multiplication(a: Array < Array < Int >> ,
b: Array < Array < Int >> ): Unit
{
// Get the size
val row: Int = a.count();
val col: Int = a[0].count();
// This matrix are store the result of multiplication
var result: Array < Array < Int >> = Array(row)
{
Array(col)
{
0
}
};
var i: Int = 0;
while (i < row)
{
var j: Int = 0;
while (j < col)
{
// Set the initial value of new matrix element
result[i][j] = 0;
var k: Int = 0;
while (k < row)
{
// Multiply matrix A [i] row and [k] columns to
// the Matrix B [k] columns and [j] rows.
result[i][j] += a[i][k] * b[k][j];
k += 1;
}
j += 1;
}
i += 1;
}
println(" Matrix A");
// Print element of matrix x
Multiply.printRecord(a);
println(" Matrix B");
// Print element of matrix y
Multiply.printRecord(b);
println(" Matrix [(A) x (B)]");
// Display resultant matrix
Multiply.printRecord(result);
}
}
}
fun main(args: Array < String > ): Unit
{
// Define matrix A
val a: Array < Array < Int >> = arrayOf(
arrayOf(1, 2, 3),
arrayOf(6, 1, 2),
arrayOf(5, 4, 3)
);
// Define matrix B
val b: Array < Array < Int >> = arrayOf(
arrayOf(3, 1, 3),
arrayOf(1, 1, 2),
arrayOf(2, 2, 3)
);
Multiply.multiplication(a, b);
}
Output
Matrix A
--------------
1 2 3
6 1 2
5 4 3
Matrix B
--------------
3 1 3
1 1 2
2 2 3
Matrix [(A) x (B)]
--------------
11 9 16
23 11 26
25 15 32
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment