Interchange the diagonal of a matrix in scala

Scala program for Interchange the diagonal of a matrix. Here mentioned other language solution.
/*
Scala program for
Swap diagonal elements of matrix using recursion
*/
class Exchange()
{
// Method which are perform swap operation
// Here x and y indicate start and end rows
// p and q indicates start and end columns
def swapDiagonal(matrix: Array[Array[Int]],
x: Int, y: Int, p: Int, q: Int): Unit = {
if (x >= y || p >= q)
{
return;
}
var temp: Int = matrix(x)(p);
// Swap the element value
matrix(x)(p) = matrix(x)(q);
matrix(x)(q) = temp;
temp = matrix(y)(p);
// Swap the element value
matrix(y)(p) = matrix(y)(q);
matrix(y)(q) = temp;
swapDiagonal(matrix, x + 1, y - 1, p + 1, q - 1);
}
// Display matrix elements
def showMatrix(matrix: Array[Array[Int]], size: Int): Unit = {
var i: Int = 0;
// iterate rows
while (i < size)
{
var j: Int = 0;
// iterate columns
while (j < size)
{
// Display element value
print(" " + matrix(i)(j));
j += 1;
}
// include new line
println();
i += 1;
}
// include new line
println();
}
}
object Main
{
def main(args: Array[String]): Unit = {
// Define matrix element
var matrix: Array[Array[Int]] = Array(
Array(1, 2, 3, 4),
Array(5, 6, 7, 8),
Array(9, 10, 11, 12),
Array(13, 14, 15, 16)
);
// Assume N X N matrix
var n: Int = matrix.length;
var task = new Exchange();
// Display element
task.showMatrix(matrix, n);
// interchange request
task.swapDiagonal(matrix, 0, n - 1, 0, n - 1);
// Display element
task.showMatrix(matrix, n);
}
}
Output
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13
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